Example #1
0
        internal Profile(int sides, float profileStart, float profileEnd, float hollow, int hollowSides, bool createFaces, bool calcVertexNormals)
        {
            this.calcVertexNormals = calcVertexNormals;
            this.coords = new List<Coord>();
            this.faces = new List<Face>();
            this.vertexNormals = new List<Coord>();
            this.us = new List<float>();
            this.faceUVs = new List<UVCoord>();
            this.faceNumbers = new List<int>();

            Coord center = new Coord(0.0f, 0.0f, 0.0f);
            //bool hasCenter = false;

            List<Coord> hollowCoords = new List<Coord>();
            List<Coord> hollowNormals = new List<Coord>();
            List<float> hollowUs = new List<float>();

            if (calcVertexNormals)
            {
                this.outerCoordIndices = new List<int>();
                this.hollowCoordIndices = new List<int>();
                this.cut1CoordIndices = new List<int>();
                this.cut2CoordIndices = new List<int>();
            }

            bool hasHollow = (hollow > 0.0f);

            bool hasProfileCut = (profileStart > 0.0f || profileEnd < 1.0f);

            AngleList angles = new AngleList();
            AngleList hollowAngles = new AngleList();

            float xScale = 0.5f;
            float yScale = 0.5f;
            if (sides == 4)  // corners of a square are sqrt(2) from center
            {
                xScale = 0.707f;
                yScale = 0.707f;
            }

            float startAngle = profileStart * twoPi;
            float stopAngle = profileEnd * twoPi;

            try { angles.makeAngles(sides, startAngle, stopAngle); }
            catch (Exception ex)
            {

                errorMessage = "makeAngles failed: Exception: " + ex.ToString()
                + "\nsides: " + sides.ToString() + " startAngle: " + startAngle.ToString() + " stopAngle: " + stopAngle.ToString();

                return;
            }

            this.numOuterVerts = angles.angles.Count;

            // flag to create as few triangles as possible for 3 or 4 side profile
            bool simpleFace = (sides < 5 && !hasHollow && !hasProfileCut);

            if (hasHollow)
            {
                if (sides == hollowSides)
                    hollowAngles = angles;
                else
                {
                    try { hollowAngles.makeAngles(hollowSides, startAngle, stopAngle); }
                    catch (Exception ex)
                    {
                        errorMessage = "makeAngles failed: Exception: " + ex.ToString()
                        + "\nsides: " + sides.ToString() + " startAngle: " + startAngle.ToString() + " stopAngle: " + stopAngle.ToString();

                        return;
                    }
                }
                this.numHollowVerts = hollowAngles.angles.Count;
            }
            else if (!simpleFace)
            {
                this.coords.Add(center);
                //hasCenter = true;
                if (this.calcVertexNormals)
                    this.vertexNormals.Add(new Coord(0.0f, 0.0f, 1.0f));
                this.us.Add(0.0f);
            }

            float z = 0.0f;

            Angle angle;
            Coord newVert = new Coord();
            if (hasHollow && hollowSides != sides)
            {
                int numHollowAngles = hollowAngles.angles.Count;
                for (int i = 0; i < numHollowAngles; i++)
                {
                    angle = hollowAngles.angles[i];
                    newVert.X = hollow * xScale * angle.X;
                    newVert.Y = hollow * yScale * angle.Y;
                    newVert.Z = z;

                    hollowCoords.Add(newVert);
                    if (this.calcVertexNormals)
                    {
                        if (hollowSides < 5)
                            hollowNormals.Add(hollowAngles.normals[i].Invert());
                        else
                            hollowNormals.Add(new Coord(-angle.X, -angle.Y, 0.0f));

                        hollowUs.Add(angle.angle * hollow);
                    }
                }
            }

            int index = 0;
            int numAngles = angles.angles.Count;

            for (int i = 0; i < numAngles; i++)
            {
                angle = angles.angles[i];
                newVert.X = angle.X * xScale;
                newVert.Y = angle.Y * yScale;
                newVert.Z = z;
                this.coords.Add(newVert);
                if (this.calcVertexNormals)
                {
                    this.outerCoordIndices.Add(this.coords.Count - 1);

                    if (sides < 5)
                    {
                        this.vertexNormals.Add(angles.normals[i]);
                        float u = angle.angle;
                        this.us.Add(u);
                    }
                    else
                    {
                        this.vertexNormals.Add(new Coord(angle.X, angle.Y, 0.0f));
                        this.us.Add(angle.angle);
                    }
                }

                if (hasHollow)
                {
                    if (hollowSides == sides)
                    {
                        newVert.X *= hollow;
                        newVert.Y *= hollow;
                        newVert.Z = z;
                        hollowCoords.Add(newVert);
                        if (this.calcVertexNormals)
                        {
                            if (sides < 5)
                            {
                                hollowNormals.Add(angles.normals[i].Invert());
                            }

                            else
                                hollowNormals.Add(new Coord(-angle.X, -angle.Y, 0.0f));

                            hollowUs.Add(angle.angle * hollow);
                        }
                    }
                }
                else if (!simpleFace && createFaces && angle.angle > 0.0001f)
                {
                    Face newFace = new Face();
                    newFace.v1 = 0;
                    newFace.v2 = index;
                    newFace.v3 = index + 1;

                    this.faces.Add(newFace);
                }
                index += 1;
            }

            if (hasHollow)
            {
                hollowCoords.Reverse();
                if (this.calcVertexNormals)
                {
                    hollowNormals.Reverse();
                    hollowUs.Reverse();
                }

                if (createFaces)
                {
                    //int numOuterVerts = this.coords.Count;
                    //numOuterVerts = this.coords.Count;
                    //int numHollowVerts = hollowCoords.Count;
                    int numTotalVerts = this.numOuterVerts + this.numHollowVerts;

                    if (this.numOuterVerts == this.numHollowVerts)
                    {
                        Face newFace = new Face();

                        for (int coordIndex = 0; coordIndex < this.numOuterVerts - 1; coordIndex++)
                        {
                            newFace.v1 = coordIndex;
                            newFace.v2 = coordIndex + 1;
                            newFace.v3 = numTotalVerts - coordIndex - 1;
                            this.faces.Add(newFace);

                            newFace.v1 = coordIndex + 1;
                            newFace.v2 = numTotalVerts - coordIndex - 2;
                            newFace.v3 = numTotalVerts - coordIndex - 1;
                            this.faces.Add(newFace);
                        }
                    }
                    else
                    {
                        if (this.numOuterVerts < this.numHollowVerts)
                        {
                            Face newFace = new Face();
                            int j = 0; // j is the index for outer vertices
                            int maxJ = this.numOuterVerts - 1;
                            for (int i = 0; i < this.numHollowVerts; i++) // i is the index for inner vertices
                            {
                                if (j < maxJ)
                                    if (angles.angles[j + 1].angle - hollowAngles.angles[i].angle < hollowAngles.angles[i].angle - angles.angles[j].angle + 0.000001f)
                                    {
                                        newFace.v1 = numTotalVerts - i - 1;
                                        newFace.v2 = j;
                                        newFace.v3 = j + 1;

                                        this.faces.Add(newFace);
                                        j += 1;
                                    }

                                newFace.v1 = j;
                                newFace.v2 = numTotalVerts - i - 2;
                                newFace.v3 = numTotalVerts - i - 1;

                                this.faces.Add(newFace);
                            }
                        }
                        else // numHollowVerts < numOuterVerts
                        {
                            Face newFace = new Face();
                            int j = 0; // j is the index for inner vertices
                            int maxJ = this.numHollowVerts - 1;
                            for (int i = 0; i < this.numOuterVerts; i++)
                            {
                                if (j < maxJ)
                                    if (hollowAngles.angles[j + 1].angle - angles.angles[i].angle < angles.angles[i].angle - hollowAngles.angles[j].angle + 0.000001f)
                                    {
                                        newFace.v1 = i;
                                        newFace.v2 = numTotalVerts - j - 2;
                                        newFace.v3 = numTotalVerts - j - 1;

                                        this.faces.Add(newFace);
                                        j += 1;
                                    }

                                newFace.v1 = numTotalVerts - j - 1;
                                newFace.v2 = i;
                                newFace.v3 = i + 1;

                                this.faces.Add(newFace);
                            }
                        }
                    }
                }

                if (calcVertexNormals)
                {
                    foreach (Coord hc in hollowCoords)
                    {
                        this.coords.Add(hc);
                        hollowCoordIndices.Add(this.coords.Count - 1);
                    }
                }
                else
                    this.coords.AddRange(hollowCoords);

                if (this.calcVertexNormals)
                {
                    this.vertexNormals.AddRange(hollowNormals);
                    this.us.AddRange(hollowUs);

                }
            }

            if (simpleFace && createFaces)
            {
                if (sides == 3)
                    this.faces.Add(new Face(0, 1, 2));
                else if (sides == 4)
                {
                    this.faces.Add(new Face(0, 1, 2));
                    this.faces.Add(new Face(0, 2, 3));
                }
            }

            if (calcVertexNormals && hasProfileCut)
            {
                if (hasHollow)
                {
                    int lastOuterVertIndex = this.numOuterVerts - 1;

                    this.cut1CoordIndices.Add(0);
                    this.cut1CoordIndices.Add(this.coords.Count - 1);

                    this.cut2CoordIndices.Add(lastOuterVertIndex + 1);
                    this.cut2CoordIndices.Add(lastOuterVertIndex);

                    this.cutNormal1.X = this.coords[0].Y - this.coords[this.coords.Count - 1].Y;
                    this.cutNormal1.Y = -(this.coords[0].X - this.coords[this.coords.Count - 1].X);

                    this.cutNormal2.X = this.coords[lastOuterVertIndex + 1].Y - this.coords[lastOuterVertIndex].Y;
                    this.cutNormal2.Y = -(this.coords[lastOuterVertIndex + 1].X - this.coords[lastOuterVertIndex].X);
                }

                else
                {
                    this.cutNormal1.X = this.vertexNormals[1].Y;
                    this.cutNormal1.Y = -this.vertexNormals[1].X;

                    this.cutNormal2.X = -this.vertexNormals[this.vertexNormals.Count - 2].Y;
                    this.cutNormal2.Y = this.vertexNormals[this.vertexNormals.Count - 2].X;

                }
                this.cutNormal1.Normalize();
                this.cutNormal2.Normalize();
            }

            this.MakeFaceUVs();

            hollowCoords = null;
            hollowNormals = null;
            hollowUs = null;

            if (calcVertexNormals)
            { // calculate prim face numbers

                // face number order is top, outer, hollow, bottom, start cut, end cut
                // I know it's ugly but so is the whole concept of prim face numbers

                int faceNum = 1; // start with outer faces
                int startVert = hasProfileCut && !hasHollow ? 1 : 0;
                if (startVert > 0)
                    this.faceNumbers.Add(-1);
                for (int i = 0; i < this.numOuterVerts - 1; i++)
                    this.faceNumbers.Add(sides < 5 ? faceNum++ : faceNum);

                //if (!hasHollow && !hasProfileCut)
                //    this.bottomFaceNumber = faceNum++;

                this.faceNumbers.Add(hasProfileCut ? -1 : faceNum++);

                if (sides > 4 && (hasHollow || hasProfileCut))
                    faceNum++;

                if (hasHollow)
                {
                    for (int i = 0; i < this.numHollowVerts; i++)
                        this.faceNumbers.Add(faceNum);

                    faceNum++;
                }
                //if (hasProfileCut || hasHollow)
                //    this.bottomFaceNumber = faceNum++;
                this.bottomFaceNumber = faceNum++;

                if (hasHollow && hasProfileCut)
                    this.faceNumbers.Add(faceNum++);
                for (int i = 0; i < this.faceNumbers.Count; i++)
                    if (this.faceNumbers[i] == -1)
                        this.faceNumbers[i] = faceNum++;


                this.numPrimFaces = faceNum;
            }

        }
Example #2
0
        /// <summary>
        /// Extrudes a profile along a path.
        /// </summary>
        public void Extrude(PathType pathType)
        {
            this.coords = new List<Coord>();
            this.faces = new List<Face>();

            if (this.viewerMode)
            {
                this.viewerFaces = new List<ViewerFace>();
                this.calcVertexNormals = true;
            }

            if (this.calcVertexNormals)
                this.normals = new List<Coord>();

            int steps = 1;

            float length = this.pathCutEnd - this.pathCutBegin;
            normalsProcessed = false;

            if (this.viewerMode && this.sides == 3)
            {
                // prisms don't taper well so add some vertical resolution
                // other prims may benefit from this but just do prisms for now
                if (Math.Abs(this.taperX) > 0.01 || Math.Abs(this.taperY) > 0.01)
                    steps = (int)(steps * 4.5 * length);
            }


            float twistBegin = this.twistBegin / 360.0f * twoPi;
            float twistEnd = this.twistEnd / 360.0f * twoPi;
            float twistTotal = twistEnd - twistBegin;
            float twistTotalAbs = Math.Abs(twistTotal);
            if (twistTotalAbs > 0.01f)
                steps += (int)(twistTotalAbs * 3.66); //  dahlia's magic number

            float hollow = this.hollow;

            // sanity checks
            float initialProfileRot = 0.0f;
            if (pathType == PathType.Circular)
            {
                if (this.sides == 3)
                {
                    initialProfileRot = (float)Math.PI;
                    if (this.hollowSides == 4)
                    {
                        if (hollow > 0.7f)
                            hollow = 0.7f;
                        hollow *= 0.707f;
                    }
                    else hollow *= 0.5f;
                }
                else if (this.sides == 4)
                {
                    initialProfileRot = 0.25f * (float)Math.PI;
                    if (this.hollowSides != 4)
                        hollow *= 0.707f;
                }
                else if (this.sides > 4)
                {
                    initialProfileRot = (float)Math.PI;
                    if (this.hollowSides == 4)
                    {
                        if (hollow > 0.7f)
                            hollow = 0.7f;
                        hollow /= 0.7f;
                    }
                }
            }
            else
            {
                if (this.sides == 3)
                {
                    if (this.hollowSides == 4)
                    {
                        if (hollow > 0.7f)
                            hollow = 0.7f;
                        hollow *= 0.707f;
                    }
                    else hollow *= 0.5f;
                }
                else if (this.sides == 4)
                {
                    initialProfileRot = 1.25f * (float)Math.PI;
                    if (this.hollowSides != 4)
                        hollow *= 0.707f;
                }
                else if (this.sides == 24 && this.hollowSides == 4)
                    hollow *= 1.414f;
            }

            Profile profile = new Profile(this.sides, this.profileStart, this.profileEnd, hollow, this.hollowSides, true, calcVertexNormals);
            this.errorMessage = profile.errorMessage;

            this.numPrimFaces = profile.numPrimFaces;

            int cut1Vert = -1;
            int cut2Vert = -1;
            if (hasProfileCut)
            {
                cut1Vert = hasHollow ? profile.coords.Count - 1 : 0;
                cut2Vert = hasHollow ? profile.numOuterVerts - 1 : profile.numOuterVerts;
            }

            if (initialProfileRot != 0.0f)
            {
                profile.AddRot(new Quat(new Coord(0.0f, 0.0f, 1.0f), initialProfileRot));
                if (viewerMode)
                    profile.MakeFaceUVs();
            }

            Coord lastCutNormal1 = new Coord();
            Coord lastCutNormal2 = new Coord();
            float lastV = 1.0f;

            Path path = new Path();
            path.twistBegin = twistBegin;
            path.twistEnd = twistEnd;
            path.topShearX = topShearX;
            path.topShearY = topShearY;
            path.pathCutBegin = pathCutBegin;
            path.pathCutEnd = pathCutEnd;
            path.dimpleBegin = dimpleBegin;
            path.dimpleEnd = dimpleEnd;
            path.skew = skew;
            path.holeSizeX = holeSizeX;
            path.holeSizeY = holeSizeY;
            path.taperX = taperX;
            path.taperY = taperY;
            path.radius = radius;
            path.revolutions = revolutions;
            path.stepsPerRevolution = stepsPerRevolution;

            path.Create(pathType, steps);

            bool needEndFaces = false;
            if (pathType == PathType.Circular)
            {
                needEndFaces = false;
                if (this.pathCutBegin != 0.0f || this.pathCutEnd != 1.0f)
                    needEndFaces = true;
                else if (this.taperX != 0.0f || this.taperY != 0.0f)
                    needEndFaces = true;
                else if (this.skew != 0.0f)
                    needEndFaces = true;
                else if (twistTotal != 0.0f)
                    needEndFaces = true;
                else if (this.radius != 0.0f)
                    needEndFaces = true;
            }
            else needEndFaces = true;

            for (int nodeIndex = 0; nodeIndex < path.pathNodes.Count; nodeIndex++)
            {
                PathNode node = path.pathNodes[nodeIndex];
                Profile newLayer = profile.Copy();
                newLayer.Scale(node.xScale, node.yScale);

                newLayer.AddRot(node.rotation);
                newLayer.AddPos(node.position);

                if (needEndFaces && nodeIndex == 0)
                {
                    newLayer.FlipNormals();

                    // add the top faces to the viewerFaces list here
                    if (this.viewerMode)
                    {
                        Coord faceNormal = newLayer.faceNormal;
                        ViewerFace newViewerFace = new ViewerFace(profile.bottomFaceNumber);
                        int numFaces = newLayer.faces.Count;
                        List<Face> faces = newLayer.faces;

                        for (int i = 0; i < numFaces; i++)
                        {
                            Face face = faces[i];
                            newViewerFace.v1 = newLayer.coords[face.v1];
                            newViewerFace.v2 = newLayer.coords[face.v2];
                            newViewerFace.v3 = newLayer.coords[face.v3];

                            newViewerFace.coordIndex1 = face.v1;
                            newViewerFace.coordIndex2 = face.v2;
                            newViewerFace.coordIndex3 = face.v3;

                            newViewerFace.n1 = faceNormal;
                            newViewerFace.n2 = faceNormal;
                            newViewerFace.n3 = faceNormal;

                            newViewerFace.uv1 = newLayer.faceUVs[face.v1];
                            newViewerFace.uv2 = newLayer.faceUVs[face.v2];
                            newViewerFace.uv3 = newLayer.faceUVs[face.v3];

                            this.viewerFaces.Add(newViewerFace);
                        }
                    }
                } // if (nodeIndex == 0)

                // append this layer

                int coordsLen = this.coords.Count;
                newLayer.AddValue2FaceVertexIndices(coordsLen);

                this.coords.AddRange(newLayer.coords);

                if (this.calcVertexNormals)
                {
                    newLayer.AddValue2FaceNormalIndices(this.normals.Count);
                    this.normals.AddRange(newLayer.vertexNormals);
                }

                if (node.percentOfPath < this.pathCutBegin + 0.01f || node.percentOfPath > this.pathCutEnd - 0.01f)
                    this.faces.AddRange(newLayer.faces);

                // fill faces between layers

                int numVerts = newLayer.coords.Count;
                Face newFace = new Face();

                if (nodeIndex > 0)
                {
                    int startVert = coordsLen + 1;
                    int endVert = this.coords.Count;

                    if (sides < 5 || this.hasProfileCut || hollow > 0.0f)
                        startVert--;

                    for (int i = startVert; i < endVert; i++)
                    {
                        int iNext = i + 1;
                        if (i == endVert - 1)
                            iNext = startVert;

                        int whichVert = i - startVert;

                        newFace.v1 = i;
                        newFace.v2 = i - numVerts;
                        newFace.v3 = iNext - numVerts;
                        this.faces.Add(newFace);

                        newFace.v2 = iNext - numVerts;
                        newFace.v3 = iNext;
                        this.faces.Add(newFace);

                        if (this.viewerMode)
                        {
                            // add the side faces to the list of viewerFaces here

                            int primFaceNum = profile.faceNumbers[whichVert];
                            if (!needEndFaces)
                                primFaceNum -= 1;

                            ViewerFace newViewerFace1 = new ViewerFace(primFaceNum);
                            ViewerFace newViewerFace2 = new ViewerFace(primFaceNum);

                            float u1 = newLayer.us[whichVert];
                            float u2 = 1.0f;
                            if (whichVert < newLayer.us.Count - 1)
                                u2 = newLayer.us[whichVert + 1];

                            if (whichVert == cut1Vert || whichVert == cut2Vert)
                            {
                                u1 = 0.0f;
                                u2 = 1.0f;
                            }
                            else if (sides < 5)
                            {
                                if (whichVert < profile.numOuterVerts)
                                { // boxes and prisms have one texture face per side of the prim, so the U values have to be scaled
                                    // to reflect the entire texture width
                                    u1 *= sides;
                                    u2 *= sides;
                                    u2 -= (int)u1;
                                    u1 -= (int)u1;
                                    if (u2 < 0.1f)
                                        u2 = 1.0f;
                                }
                                else if (whichVert > profile.coords.Count - profile.numHollowVerts - 1)
                                {
                                    u1 *= 2.0f;
                                    u2 *= 2.0f;
                                }
                            }

                            newViewerFace1.uv1.U = u1;
                            newViewerFace1.uv2.U = u1;
                            newViewerFace1.uv3.U = u2;

                            newViewerFace1.uv1.V = 1.0f - node.percentOfPath;
                            newViewerFace1.uv2.V = lastV;
                            newViewerFace1.uv3.V = lastV;

                            newViewerFace2.uv1.U = u1;
                            newViewerFace2.uv2.U = u2;
                            newViewerFace2.uv3.U = u2;

                            newViewerFace2.uv1.V = 1.0f - node.percentOfPath;
                            newViewerFace2.uv2.V = lastV;
                            newViewerFace2.uv3.V = 1.0f - node.percentOfPath;

                            newViewerFace1.v1 = this.coords[i];
                            newViewerFace1.v2 = this.coords[i - numVerts];
                            newViewerFace1.v3 = this.coords[iNext - numVerts];

                            newViewerFace2.v1 = this.coords[i];
                            newViewerFace2.v2 = this.coords[iNext - numVerts];
                            newViewerFace2.v3 = this.coords[iNext];

                            newViewerFace1.coordIndex1 = i;
                            newViewerFace1.coordIndex2 = i - numVerts;
                            newViewerFace1.coordIndex3 = iNext - numVerts;

                            newViewerFace2.coordIndex1 = i;
                            newViewerFace2.coordIndex2 = iNext - numVerts;
                            newViewerFace2.coordIndex3 = iNext;

                            // profile cut faces
                            if (whichVert == cut1Vert)
                            {
                                newViewerFace1.n1 = newLayer.cutNormal1;
                                newViewerFace1.n2 = newViewerFace1.n3 = lastCutNormal1;

                                newViewerFace2.n1 = newViewerFace2.n3 = newLayer.cutNormal1;
                                newViewerFace2.n2 = lastCutNormal1;
                            }
                            else if (whichVert == cut2Vert)
                            {
                                newViewerFace1.n1 = newLayer.cutNormal2;
                                newViewerFace1.n2 = newViewerFace1.n3 = lastCutNormal2;

                                newViewerFace2.n1 = newViewerFace2.n3 = newLayer.cutNormal2;
                                newViewerFace2.n2 = lastCutNormal2;
                            }

                            else // outer and hollow faces
                            {
                                if ((sides < 5 && whichVert < newLayer.numOuterVerts) || (hollowSides < 5 && whichVert >= newLayer.numOuterVerts))
                                { // looks terrible when path is twisted... need vertex normals here
                                    newViewerFace1.CalcSurfaceNormal();
                                    newViewerFace2.CalcSurfaceNormal();
                                }
                                else
                                {
                                    newViewerFace1.n1 = this.normals[i];
                                    newViewerFace1.n2 = this.normals[i - numVerts];
                                    newViewerFace1.n3 = this.normals[iNext - numVerts];

                                    newViewerFace2.n1 = this.normals[i];
                                    newViewerFace2.n2 = this.normals[iNext - numVerts];
                                    newViewerFace2.n3 = this.normals[iNext];
                                }
                            }

                            this.viewerFaces.Add(newViewerFace1);
                            this.viewerFaces.Add(newViewerFace2);

                        }
                    }
                }

                lastCutNormal1 = newLayer.cutNormal1;
                lastCutNormal2 = newLayer.cutNormal2;
                lastV = 1.0f - node.percentOfPath;

                if (needEndFaces && nodeIndex == path.pathNodes.Count - 1 && viewerMode)
                {
                    // add the top faces to the viewerFaces list here
                    Coord faceNormal = newLayer.faceNormal;
                    ViewerFace newViewerFace = new ViewerFace();
                    newViewerFace.primFaceNumber = 0;
                    int numFaces = newLayer.faces.Count;
                    List<Face> faces = newLayer.faces;

                    for (int i = 0; i < numFaces; i++)
                    {
                        Face face = faces[i];
                        newViewerFace.v1 = newLayer.coords[face.v1 - coordsLen];
                        newViewerFace.v2 = newLayer.coords[face.v2 - coordsLen];
                        newViewerFace.v3 = newLayer.coords[face.v3 - coordsLen];

                        newViewerFace.coordIndex1 = face.v1 - coordsLen;
                        newViewerFace.coordIndex2 = face.v2 - coordsLen;
                        newViewerFace.coordIndex3 = face.v3 - coordsLen;

                        newViewerFace.n1 = faceNormal;
                        newViewerFace.n2 = faceNormal;
                        newViewerFace.n3 = faceNormal;

                        newViewerFace.uv1 = newLayer.faceUVs[face.v1 - coordsLen];
                        newViewerFace.uv2 = newLayer.faceUVs[face.v2 - coordsLen];
                        newViewerFace.uv3 = newLayer.faceUVs[face.v3 - coordsLen];

                        this.viewerFaces.Add(newViewerFace);
                    }
                }


            } // for (int nodeIndex = 0; nodeIndex < path.pathNodes.Count; nodeIndex++)

        }
Example #3
0
 private Coord SurfaceNormal(Face face)
 {
     return SurfaceNormal(this.coords[face.v1], this.coords[face.v2], this.coords[face.v3]);
 }
Example #4
0
        private void _SculptMesh(List<List<Coord>> rows, SculptType sculptType, bool viewerMode, bool mirror,
                                 bool invert)
        {
            coords = new List<Coord>();
            faces = new List<Face>();
            normals = new List<Coord>();
            uvs = new List<UVCoord>();

            sculptType = (SculptType) (((int) sculptType) & 0x07);

            if (mirror)
                invert = !invert;

            viewerFaces = new List<ViewerFace>();

            int width = rows[0].Count;

            int p1, p2, p3, p4;

            int imageX, imageY;

            if (sculptType != SculptType.plane)
            {
                if (rows.Count%2 == 0)
                {
                    foreach (List<Coord> t in rows)
                        t.Add(t[0]);
                }
                else
                {
                    int lastIndex = rows[0].Count - 1;

                    foreach (List<Coord> t in rows)
                        t[0] = t[lastIndex];
                }
            }

            Coord topPole = rows[0][width/2];
            Coord bottomPole = rows[rows.Count - 1][width/2];

            if (sculptType == SculptType.sphere)
            {
                if (rows.Count%2 == 0)
                {
                    int count = rows[0].Count;
                    List<Coord> topPoleRow = new List<Coord>(count);
                    List<Coord> bottomPoleRow = new List<Coord>(count);

                    for (int i = 0; i < count; i++)
                    {
                        topPoleRow.Add(topPole);
                        bottomPoleRow.Add(bottomPole);
                    }
                    rows.Insert(0, topPoleRow);
                    rows.Add(bottomPoleRow);
                }
                else
                {
                    int count = rows[0].Count;

                    List<Coord> topPoleRow = rows[0];
                    List<Coord> bottomPoleRow = rows[rows.Count - 1];

                    for (int i = 0; i < count; i++)
                    {
                        topPoleRow[i] = topPole;
                        bottomPoleRow[i] = bottomPole;
                    }
                }
            }

            if (sculptType == SculptType.torus)
                rows.Add(rows[0]);

            int coordsDown = rows.Count;
            int coordsAcross = rows[0].Count;

            float widthUnit = 1.0f/(coordsAcross - 1);
            float heightUnit = 1.0f/(coordsDown - 1);

            for (imageY = 0; imageY < coordsDown; imageY++)
            {
                int rowOffset = imageY*coordsAcross;

                for (imageX = 0; imageX < coordsAcross; imageX++)
                {
                    /*
                    *   p1-----p2
                    *   | \ f2 |
                    *   |   \  |
                    *   | f1  \|
                    *   p3-----p4
                    */

                    p4 = rowOffset + imageX;
                    p3 = p4 - 1;

                    p2 = p4 - coordsAcross;
                    p1 = p3 - coordsAcross;

                    this.coords.Add(rows[imageY][imageX]);
                    if (viewerMode)
                    {
                        this.normals.Add(new Coord());
                        this.uvs.Add(new UVCoord(widthUnit*imageX, heightUnit*imageY));
                    }

                    if (imageY > 0 && imageX > 0)
                    {
                        Face f1, f2;

                        if (viewerMode)
                        {
                            if (invert)
                            {
                                f1 = new Face(p1, p4, p3, p1, p4, p3) {uv1 = p1, uv2 = p4, uv3 = p3};

                                f2 = new Face(p1, p2, p4, p1, p2, p4) {uv1 = p1, uv2 = p2, uv3 = p4};
                            }
                            else
                            {
                                f1 = new Face(p1, p3, p4, p1, p3, p4) {uv1 = p1, uv2 = p3, uv3 = p4};

                                f2 = new Face(p1, p4, p2, p1, p4, p2) {uv1 = p1, uv2 = p4, uv3 = p2};
                            }
                        }
                        else
                        {
                            if (invert)
                            {
                                f1 = new Face(p1, p4, p3);
                                f2 = new Face(p1, p2, p4);
                            }
                            else
                            {
                                f1 = new Face(p1, p3, p4);
                                f2 = new Face(p1, p4, p2);
                            }
                        }

                        this.faces.Add(f1);
                        this.faces.Add(f2);
                    }
                }
            }

            if (viewerMode)
                calcVertexNormals(sculptType, coordsAcross, coordsDown);
        }
Example #5
0
        /// <summary>
        ///   ** Experimental ** May disappear from future versions ** not recommeneded for use in applications
        ///   Construct a sculpt mesh from a 2D array of floats
        /// </summary>
        /// <param name = "zMap"></param>
        /// <param name = "xBegin"></param>
        /// <param name = "xEnd"></param>
        /// <param name = "yBegin"></param>
        /// <param name = "yEnd"></param>
        /// <param name = "viewerMode"></param>
        public SculptMesh(float[,] zMap, float xBegin, float xEnd, float yBegin, float yEnd, bool viewerMode)
        {
            float xStep, yStep;
            float uStep, vStep;

            int numYElements = zMap.GetLength(0);
            int numXElements = zMap.GetLength(1);

            try
            {
                xStep = (xEnd - xBegin)/(numXElements - 1);
                yStep = (yEnd - yBegin)/(numYElements - 1);

                uStep = 1.0f/(numXElements - 1);
                vStep = 1.0f/(numYElements - 1);
            }
            catch (DivideByZeroException)
            {
                return;
            }

            coords = new List<Coord>();
            faces = new List<Face>();
            normals = new List<Coord>();
            uvs = new List<UVCoord>();

            viewerFaces = new List<ViewerFace>();

            int p1, p2, p3, p4;

            int x, y;
            int xStart = 0, yStart = 0;

            for (y = yStart; y < numYElements; y++)
            {
                int rowOffset = y*numXElements;

                for (x = xStart; x < numXElements; x++)
                {
                    /*
                    *   p1-----p2
                    *   | \ f2 |
                    *   |   \  |
                    *   | f1  \|
                    *   p3-----p4
                    */

                    p4 = rowOffset + x;
                    p3 = p4 - 1;

                    p2 = p4 - numXElements;
                    p1 = p3 - numXElements;
                    Coord c = new Coord(xBegin + x*xStep, yBegin + y*yStep, zMap[y, x]);
                    this.coords.Add(c);
                    if (viewerMode)
                    {
                        this.normals.Add(new Coord());
                        this.uvs.Add(new UVCoord(uStep*x, 1.0f - vStep*y));
                    }

                    if (y > 0 && x > 0)
                    {
                        Face f1, f2;

                        if (viewerMode)
                        {
                            f1 = new Face(p1, p4, p3, p1, p4, p3) {uv1 = p1, uv2 = p4, uv3 = p3};

                            f2 = new Face(p1, p2, p4, p1, p2, p4) {uv1 = p1, uv2 = p2, uv3 = p4};
                        }
                        else
                        {
                            f1 = new Face(p1, p4, p3);
                            f2 = new Face(p1, p2, p4);
                        }

                        this.faces.Add(f1);
                        this.faces.Add(f2);
                    }
                }
            }

            if (viewerMode)
                calcVertexNormals(SculptType.plane, numXElements, numYElements);
        }
Example #6
0
        /// <summary>
        /// Add a submesh to an existing list of coords and faces.
        /// </summary>
        /// <param name="subMeshData"></param>
        /// <param name="size">Size of entire object</param>
        /// <param name="coords"></param>
        /// <param name="faces"></param>
        private void AddSubMesh(OSDMap subMeshData, List<Coord> coords, List<Face> faces)
        {
    //                                    Console.WriteLine("subMeshMap for {0} - {1}", primName, Util.GetFormattedXml((OSD)subMeshMap));
    
            // As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level
            // of Detail Blocks (maps) contain just a NoGeometry key to signal there is no
            // geometry for this submesh.
            if (subMeshData.ContainsKey("NoGeometry") && ((OSDBoolean)subMeshData["NoGeometry"]))
                return;

            OpenMetaverse.Vector3 posMax;
            OpenMetaverse.Vector3 posMin;
            if (subMeshData.ContainsKey("PositionDomain"))
            {
                posMax = ((OSDMap)subMeshData["PositionDomain"])["Max"].AsVector3();
                posMin = ((OSDMap)subMeshData["PositionDomain"])["Min"].AsVector3();
            }
            else
            {
                posMax = new Vector3(0.5f, 0.5f, 0.5f);
                posMin = new Vector3(-0.5f, -0.5f, -0.5f);
            }

            ushort faceIndexOffset = (ushort)coords.Count;

            byte[] posBytes = subMeshData["Position"].AsBinary();
            for (int i = 0; i < posBytes.Length; i += 6)
            {
                ushort uX = Utils.BytesToUInt16(posBytes, i);
                ushort uY = Utils.BytesToUInt16(posBytes, i + 2);
                ushort uZ = Utils.BytesToUInt16(posBytes, i + 4);
    
                Coord c = new Coord(
                Utils.UInt16ToFloat(uX, posMin.X, posMax.X),
                Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y),
                Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z));
    
                coords.Add(c);
            }
    
            byte[] triangleBytes = subMeshData["TriangleList"].AsBinary();
            for (int i = 0; i < triangleBytes.Length; i += 6)
            {
                ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset);
                ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset);
                ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset);
                Face f = new Face(v1, v2, v3);
                faces.Add(f);
            }
        }
Example #7
0
        /// <summary>
        /// Generate the co-ords and faces necessary to construct a mesh from the mesh data the accompanies a prim.
        /// </summary>
        /// <param name="primName"></param>
        /// <param name="primShape"></param>
        /// <param name="size"></param>
        /// <param name="coords">Coords are added to this list by the method.</param>
        /// <param name="faces">Faces are added to this list by the method.</param>
        /// <returns>true if coords and faces were successfully generated, false if not</returns>
        private bool GenerateCoordsAndFacesFromPrimMeshData(
            string primName, PrimitiveBaseShape primShape, out List<Coord> coords, out List<Face> faces, bool convex)
        {
//            m_log.DebugFormat("[MESH]: experimental mesh proxy generation for {0}", primName);

            bool usemesh = false;

            coords = new List<Coord>();
            faces = new List<Face>();
            OSD meshOsd = null;

            if (primShape.SculptData.Length <= 0)
            {
//                m_log.InfoFormat("[MESH]: asset data for {0} is zero length", primName);
                return false;
            }

            long start = 0;
            using (MemoryStream data = new MemoryStream(primShape.SculptData))
            {
                try
                {
                    OSD osd = OSDParser.DeserializeLLSDBinary(data);
                    if (osd is OSDMap)
                        meshOsd = (OSDMap)osd;
                    else
                    {
                        m_log.Warn("[Mesh}: unable to cast mesh asset to OSDMap");
                        return false;
                    }
                }
                catch (Exception e)
                {
                    m_log.Error("[MESH]: Exception deserializing mesh asset header:" + e.ToString());
                }

                start = data.Position;
            }

            if (meshOsd is OSDMap)
            {
                OSDMap physicsParms = null;
                OSDMap map = (OSDMap)meshOsd;

                if (!convex)
                {
                    if (map.ContainsKey("physics_shape"))
                        physicsParms = (OSDMap)map["physics_shape"]; // old asset format
                    else if (map.ContainsKey("physics_mesh"))
                        physicsParms = (OSDMap)map["physics_mesh"]; // new asset format

                    if (physicsParms != null)
                        usemesh = true;
                }
                
                if(!usemesh && (map.ContainsKey("physics_convex")))
                        physicsParms = (OSDMap)map["physics_convex"];
              

                if (physicsParms == null)
                {
                    m_log.Warn("[MESH]: unknown mesh type");
                    return false;
                }

                int physOffset = physicsParms["offset"].AsInteger() + (int)start;
                int physSize = physicsParms["size"].AsInteger();

                if (physOffset < 0 || physSize == 0)
                    return false; // no mesh data in asset

                OSD decodedMeshOsd = new OSD();
                byte[] meshBytes = new byte[physSize];
                System.Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize);

                try
                {
                    using (MemoryStream inMs = new MemoryStream(meshBytes))
                    {
                        using (MemoryStream outMs = new MemoryStream())
                        {
                            using (DeflateStream decompressionStream = new DeflateStream(inMs, CompressionMode.Decompress))
                            {
                                byte[] readBuffer = new byte[2048];
                                inMs.Read(readBuffer, 0, 2); // skip first 2 bytes in header
                                int readLen = 0;

                                while ((readLen = decompressionStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                                    outMs.Write(readBuffer, 0, readLen);

                                outMs.Flush();
                                outMs.Seek(0, SeekOrigin.Begin);

                                byte[] decompressedBuf = outMs.GetBuffer();

                                decodedMeshOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);  
                            }
                        }          
                    }
                }
                catch (Exception e)
                {
                    m_log.Error("[MESH]: exception decoding physical mesh prim " + primName +" : " + e.ToString());
                    return false;
                }

                if (usemesh)
                {
                    OSDArray decodedMeshOsdArray = null;

                    // physics_shape is an array of OSDMaps, one for each submesh
                    if (decodedMeshOsd is OSDArray)
                    {
//                      Console.WriteLine("decodedMeshOsd for {0} - {1}", primName, Util.GetFormattedXml(decodedMeshOsd));

                        decodedMeshOsdArray = (OSDArray)decodedMeshOsd;
                        foreach (OSD subMeshOsd in decodedMeshOsdArray)
                        {
                            if (subMeshOsd is OSDMap)
                                AddSubMesh(subMeshOsd as OSDMap, coords, faces);
                        }
                    }
                }
                else
                {
                    OSDMap cmap = (OSDMap)decodedMeshOsd;
                    if (cmap == null)
                        return false;

                    byte[] data;

                    List<float3> vs = new List<float3>();
                    PHullResult hullr = new PHullResult();
                    float3 f3;
                    Coord c;
                    Face f;
                    Vector3 range;
                    Vector3 min;

                    const float invMaxU16 = 1.0f / 65535f;
                    int t1;
                    int t2;
                    int t3;
                    int i;
                    int nverts;
                    int nindexs;

                    if (cmap.ContainsKey("Max"))
                        range = cmap["Max"].AsVector3();
                    else
                        range = new Vector3(0.5f, 0.5f, 0.5f);

                    if (cmap.ContainsKey("Min"))
                        min = cmap["Min"].AsVector3();
                    else
                        min = new Vector3(-0.5f, -0.5f, -0.5f);

                    range = range - min;
                    range *= invMaxU16;

                    if (!convex && cmap.ContainsKey("HullList") && cmap.ContainsKey("Positions"))
                    {
                        List<int> hsizes = new List<int>();
                        int totalpoints = 0;
                        data = cmap["HullList"].AsBinary();
                        for (i = 0; i < data.Length; i++)
                        {
                            t1 = data[i];
                            if (t1 == 0)
                                t1 = 256;
                            totalpoints += t1;
                            hsizes.Add(t1);
                        }

                        data = cmap["Positions"].AsBinary();
                        int ptr = 0;
                        int vertsoffset = 0;

                        if (totalpoints == data.Length / 6) // 2 bytes per coord, 3 coords per point
                        {
                            foreach (int hullsize in hsizes)
                            {
                                for (i = 0; i < hullsize; i++ )
                                {
                                    t1 = data[ptr++];
                                    t1 += data[ptr++] << 8;
                                    t2 = data[ptr++];
                                    t2 += data[ptr++] << 8;
                                    t3 = data[ptr++];
                                    t3 += data[ptr++] << 8;

                                    f3 = new float3((t1 * range.X + min.X),
                                              (t2 * range.Y + min.Y),
                                              (t3 * range.Z + min.Z));
                                    vs.Add(f3);
                                }

                                if(hullsize <3)
                                {
                                    vs.Clear();
                                    continue;
                                }

                                if (hullsize <5)
                                {
                                    foreach (float3 point in vs)
                                    {
                                        c.X = point.x;
                                        c.Y = point.y;
                                        c.Z = point.z;
                                        coords.Add(c);
                                    }
                                    f = new Face(vertsoffset, vertsoffset + 1, vertsoffset + 2);
                                    faces.Add(f);

                                    if (hullsize == 4)
                                    {
                                        // not sure about orientation..
                                        f = new Face(vertsoffset, vertsoffset + 2, vertsoffset + 3);
                                        faces.Add(f);
                                        f = new Face(vertsoffset, vertsoffset + 3, vertsoffset + 1);
                                        faces.Add(f);
                                        f = new Face(vertsoffset + 3, vertsoffset + 2, vertsoffset + 1);
                                        faces.Add(f);
                                    }
                                    vertsoffset += vs.Count;
                                    vs.Clear(); 
                                    continue;
                                }

                                if (!HullUtils.ComputeHull(vs, ref hullr, 0, 0.0f))
                                {
                                    vs.Clear();
                                    continue;
                                }

                                nverts = hullr.Vertices.Count;
                                nindexs = hullr.Indices.Count;

                                if (nindexs % 3 != 0)
                                {
                                    vs.Clear();
                                    continue;
                                }

                                for (i = 0; i < nverts; i++)
                                {
                                    c.X = hullr.Vertices[i].x;
                                    c.Y = hullr.Vertices[i].y;
                                    c.Z = hullr.Vertices[i].z;
                                    coords.Add(c);
                                }
                               
                                for (i = 0; i < nindexs; i += 3)
                                {
                                    t1 = hullr.Indices[i];
                                    if (t1 > nverts)
                                        break;
                                    t2 = hullr.Indices[i + 1];
                                    if (t2 > nverts)
                                        break;
                                    t3 = hullr.Indices[i + 2];
                                    if (t3 > nverts)
                                        break;
                                    f = new Face(vertsoffset + t1, vertsoffset + t2, vertsoffset + t3);
                                    faces.Add(f);
                                }
                                vertsoffset += nverts;
                                vs.Clear();
                            }
                        }
                        if (coords.Count > 0 && faces.Count > 0)
                            return true;                      
                    }

                    vs.Clear();

                    if (cmap.ContainsKey("BoundingVerts"))
                    {
                        data = cmap["BoundingVerts"].AsBinary();

                        for (i = 0; i < data.Length; )
                        {
                            t1 = data[i++];
                            t1 += data[i++] << 8;
                            t2 = data[i++];
                            t2 += data[i++] << 8;
                            t3 = data[i++];
                            t3 += data[i++] << 8;

                            f3 = new float3((t1 * range.X + min.X),
                                      (t2 * range.Y + min.Y),
                                      (t3 * range.Z + min.Z));
                            vs.Add(f3);
                        }

                        if (vs.Count < 3)
                        {
                            vs.Clear();
                            return false;
                        }

                        if (vs.Count < 5)
                        {
                            foreach (float3 point in vs)
                            {
                                c.X = point.x;
                                c.Y = point.y;
                                c.Z = point.z;
                                coords.Add(c);
                            }
                            f = new Face(0, 1, 2);
                            faces.Add(f);

                            if (vs.Count == 4)
                            {
                                f = new Face(0, 2, 3);
                                faces.Add(f);
                                f = new Face(0, 3, 1);
                                faces.Add(f);
                                f = new Face( 3, 2, 1);
                                faces.Add(f);
                            }
                            vs.Clear();
                            return true;
                        }

                        if (!HullUtils.ComputeHull(vs, ref hullr, 0, 0.0f))
                            return false;

                        nverts = hullr.Vertices.Count;
                        nindexs = hullr.Indices.Count;

                        if (nindexs % 3 != 0)
                            return false;

                        for (i = 0; i < nverts; i++)
                        {
                            c.X = hullr.Vertices[i].x;
                            c.Y = hullr.Vertices[i].y;
                            c.Z = hullr.Vertices[i].z;
                            coords.Add(c);
                        }
                        for (i = 0; i < nindexs; i += 3)
                        {
                            t1 = hullr.Indices[i];
                            if (t1 > nverts)
                                break;
                            t2 = hullr.Indices[i + 1];
                            if (t2 > nverts)
                                break;
                            t3 = hullr.Indices[i + 2];
                            if (t3 > nverts)
                                break;
                            f = new Face(t1, t2, t3);
                            faces.Add(f);
                        }

                        if (coords.Count > 0 && faces.Count > 0)
                            return true;
                    }
                    else
                        return false;
                }
            }

            return true;
        }
Example #8
0
        /// <summary>
        /// Extrudes a profile along a straight line path. Used for prim types box, cylinder, and prism.
        /// </summary>
        public void ExtrudeLinear()
        {
            this.coords = new List<Coord>();
            this.faces = new List<Face>();

            if (this.viewerMode)
            {
                this.viewerFaces = new List<ViewerFace>();
                this.calcVertexNormals = true;
            }

            if (this.calcVertexNormals)
                this.normals = new List<Coord>();

            int step = 0;
            int steps = 1;

            float length = this.pathCutEnd - this.pathCutBegin;
            normalsProcessed = false;

            if (this.viewerMode && this.sides == 3)
            {
                // prisms don't taper well so add some vertical resolution
                // other prims may benefit from this but just do prisms for now
                if (Math.Abs(this.taperX) > 0.01 || Math.Abs(this.taperY) > 0.01)
                    steps = (int)(steps * 4.5 * length);
            }


            float twistBegin = this.twistBegin / 360.0f * twoPi;
            float twistEnd = this.twistEnd / 360.0f * twoPi;
            float twistTotal = twistEnd - twistBegin;
            float twistTotalAbs = Math.Abs(twistTotal);
            if (twistTotalAbs > 0.01f)
                steps += (int)(twistTotalAbs * 3.66); //  dahlia's magic number

            float start = -0.5f;
            float stepSize = length / (float)steps;
            float percentOfPathMultiplier = stepSize;
            float xProfileScale = 1.0f;
            float yProfileScale = 1.0f;
            float xOffset = 0.0f;
            float yOffset = 0.0f;
            float zOffset = start;
            float xOffsetStepIncrement = this.topShearX / steps;
            float yOffsetStepIncrement = this.topShearY / steps;

            float percentOfPath = this.pathCutBegin;
            zOffset += percentOfPath;

            float hollow = this.hollow;

            // sanity checks
            float initialProfileRot = 0.0f;
            if (this.sides == 3)
            {
                if (this.hollowSides == 4)
                {
                    if (hollow > 0.7f)
                        hollow = 0.7f;
                    hollow *= 0.707f;
                }
                else hollow *= 0.5f;
            }
            else if (this.sides == 4)
            {
                initialProfileRot = 1.25f * (float)Math.PI;
                if (this.hollowSides != 4)
                    hollow *= 0.707f;
            }
            else if (this.sides == 24 && this.hollowSides == 4)
                hollow *= 1.414f;

            Profile profile = new Profile(this.sides, this.profileStart, this.profileEnd, hollow, this.hollowSides, true, calcVertexNormals);
            this.errorMessage = profile.errorMessage;

            this.numPrimFaces = profile.numPrimFaces;

            int cut1Vert = -1;
            int cut2Vert = -1;
            if (hasProfileCut)
            {
                cut1Vert = hasHollow ? profile.coords.Count - 1 : 0;
                cut2Vert = hasHollow ? profile.numOuterVerts - 1 : profile.numOuterVerts;
            }

            if (initialProfileRot != 0.0f)
            {
                profile.AddRot(new Quat(new Coord(0.0f, 0.0f, 1.0f), initialProfileRot));
                if (viewerMode)
                    profile.MakeFaceUVs();
            }

            Coord lastCutNormal1 = new Coord();
            Coord lastCutNormal2 = new Coord();
            float lastV = 1.0f;

            bool done = false;
            while (!done)
            {
                Profile newLayer = profile.Copy();

                if (this.taperX == 0.0f)
                    xProfileScale = 1.0f;
                else if (this.taperX > 0.0f)
                    xProfileScale = 1.0f - percentOfPath * this.taperX;
                else xProfileScale = 1.0f + (1.0f - percentOfPath) * this.taperX;

                if (this.taperY == 0.0f)
                    yProfileScale = 1.0f;
                else if (this.taperY > 0.0f)
                    yProfileScale = 1.0f - percentOfPath * this.taperY;
                else yProfileScale = 1.0f + (1.0f - percentOfPath) * this.taperY;

                if (xProfileScale != 1.0f || yProfileScale != 1.0f)
                    newLayer.Scale(xProfileScale, yProfileScale);

                float twist = twistBegin + twistTotal * percentOfPath;
                if (twist != 0.0f)
                    newLayer.AddRot(new Quat(new Coord(0.0f, 0.0f, 1.0f), twist));

                newLayer.AddPos(xOffset, yOffset, zOffset);

                if (step == 0)
                {
                    newLayer.FlipNormals();

                    // add the top faces to the viewerFaces list here
                    if (this.viewerMode)
                    {
                        Coord faceNormal = newLayer.faceNormal;
                        ViewerFace newViewerFace = new ViewerFace(profile.bottomFaceNumber);
                        int numFaces = newLayer.faces.Count;
                        List<Face> faces = newLayer.faces;

                        for (int i = 0; i < numFaces; i++)
                        {
                            Face face = faces[i];
                            newViewerFace.v1 = newLayer.coords[face.v1];
                            newViewerFace.v2 = newLayer.coords[face.v2];
                            newViewerFace.v3 = newLayer.coords[face.v3];

                            newViewerFace.coordIndex1 = face.v1;
                            newViewerFace.coordIndex2 = face.v2;
                            newViewerFace.coordIndex3 = face.v3;

                            newViewerFace.n1 = faceNormal;
                            newViewerFace.n2 = faceNormal;
                            newViewerFace.n3 = faceNormal;

                            newViewerFace.uv1 = newLayer.faceUVs[face.v1];
                            newViewerFace.uv2 = newLayer.faceUVs[face.v2];
                            newViewerFace.uv3 = newLayer.faceUVs[face.v3];

                            this.viewerFaces.Add(newViewerFace);
                        }
                    }
                }

                // append this layer

                int coordsLen = this.coords.Count;
                int lastCoordsLen = coordsLen;
                newLayer.AddValue2FaceVertexIndices(coordsLen);

                this.coords.AddRange(newLayer.coords);

                if (this.calcVertexNormals)
                {
                    newLayer.AddValue2FaceNormalIndices(this.normals.Count);
                    this.normals.AddRange(newLayer.vertexNormals);
                }

                if (percentOfPath < this.pathCutBegin + 0.01f || percentOfPath > this.pathCutEnd - 0.01f)
                    this.faces.AddRange(newLayer.faces);

                // fill faces between layers

                int numVerts = newLayer.coords.Count;
                Face newFace = new Face();

                if (step > 0)
                {
                    int startVert = coordsLen + 1;
                    int endVert = this.coords.Count;

                    if (sides < 5 || this.hasProfileCut || hollow > 0.0f)
                        startVert--;

                    for (int i = startVert; i < endVert; i++)
                    {
                        int iNext = i + 1;
                        if (i == endVert - 1)
                            iNext = startVert;

                        int whichVert = i - startVert;
                        //int whichVert2 = i - lastCoordsLen;

                        newFace.v1 = i;
                        newFace.v2 = i - numVerts;
                        newFace.v3 = iNext - numVerts;
                        this.faces.Add(newFace);

                        newFace.v2 = iNext - numVerts;
                        newFace.v3 = iNext;
                        this.faces.Add(newFace);

                        if (this.viewerMode)
                        {
                            // add the side faces to the list of viewerFaces here
                            //int primFaceNum = 1;
                            //if (whichVert >= sides)
                            //    primFaceNum = 2;
                            int primFaceNum = profile.faceNumbers[whichVert];

                            ViewerFace newViewerFace1 = new ViewerFace(primFaceNum);
                            ViewerFace newViewerFace2 = new ViewerFace(primFaceNum);

                            float u1 = newLayer.us[whichVert];
                            float u2 = 1.0f;
                            if (whichVert < newLayer.us.Count - 1)
                                u2 = newLayer.us[whichVert + 1];

                            if (whichVert == cut1Vert || whichVert == cut2Vert)
                            {
                                u1 = 0.0f;
                                u2 = 1.0f;
                            }
                            else if (sides < 5)
                            { // boxes and prisms have one texture face per side of the prim, so the U values have to be scaled
                                // to reflect the entire texture width
                                u1 *= sides;
                                u2 *= sides;
                                u2 -= (int)u1;
                                u1 -= (int)u1;
                                if (u2 < 0.1f)
                                    u2 = 1.0f;

                                //newViewerFace2.primFaceNumber = newViewerFace1.primFaceNumber = whichVert + 1;
                            }

                            newViewerFace1.uv1.U = u1;
                            newViewerFace1.uv2.U = u1;
                            newViewerFace1.uv3.U = u2;

                            newViewerFace1.uv1.V = 1.0f - percentOfPath;
                            newViewerFace1.uv2.V = lastV;
                            newViewerFace1.uv3.V = lastV;

                            newViewerFace2.uv1.U = u1;
                            newViewerFace2.uv2.U = u2;
                            newViewerFace2.uv3.U = u2;

                            newViewerFace2.uv1.V = 1.0f - percentOfPath;
                            newViewerFace2.uv2.V = lastV;
                            newViewerFace2.uv3.V = 1.0f - percentOfPath;

                            newViewerFace1.v1 = this.coords[i];
                            newViewerFace1.v2 = this.coords[i - numVerts];
                            newViewerFace1.v3 = this.coords[iNext - numVerts];

                            newViewerFace2.v1 = this.coords[i];
                            newViewerFace2.v2 = this.coords[iNext - numVerts];
                            newViewerFace2.v3 = this.coords[iNext];

                            newViewerFace1.coordIndex1 = i;
                            newViewerFace1.coordIndex2 = i - numVerts;
                            newViewerFace1.coordIndex3 = iNext - numVerts;

                            newViewerFace2.coordIndex1 = i;
                            newViewerFace2.coordIndex2 = iNext - numVerts;
                            newViewerFace2.coordIndex3 = iNext;

                            // profile cut faces
                            if (whichVert == cut1Vert)
                            {
                                newViewerFace1.n1 = newLayer.cutNormal1;
                                newViewerFace1.n2 = newViewerFace1.n3 = lastCutNormal1;

                                newViewerFace2.n1 = newViewerFace2.n3 = newLayer.cutNormal1;
                                newViewerFace2.n2 = lastCutNormal1;
                            }
                            else if (whichVert == cut2Vert)
                            {
                                newViewerFace1.n1 = newLayer.cutNormal2;
                                newViewerFace1.n2 = newViewerFace1.n3 = lastCutNormal2;

                                newViewerFace2.n1 = newViewerFace2.n3 = newLayer.cutNormal2;
                                newViewerFace2.n2 = lastCutNormal2;
                            }

                            else // outer and hollow faces
                            {
                                if ((sides < 5 && whichVert < newLayer.numOuterVerts) || (hollowSides < 5 && whichVert >= newLayer.numOuterVerts))
                                {
                                    newViewerFace1.CalcSurfaceNormal();
                                    newViewerFace2.CalcSurfaceNormal();
                                }
                                else
                                {
                                    newViewerFace1.n1 = this.normals[i];
                                    newViewerFace1.n2 = this.normals[i - numVerts];
                                    newViewerFace1.n3 = this.normals[iNext - numVerts];

                                    newViewerFace2.n1 = this.normals[i];
                                    newViewerFace2.n2 = this.normals[iNext - numVerts];
                                    newViewerFace2.n3 = this.normals[iNext];
                                }
                            }

                            //newViewerFace2.primFaceNumber = newViewerFace1.primFaceNumber = newLayer.faceNumbers[whichVert];

                            this.viewerFaces.Add(newViewerFace1);
                            this.viewerFaces.Add(newViewerFace2);

                        }
                    }
                }

                lastCutNormal1 = newLayer.cutNormal1;
                lastCutNormal2 = newLayer.cutNormal2;
                lastV = 1.0f - percentOfPath;

                // calc the step for the next iteration of the loop

                if (step < steps)
                {
                    step += 1;
                    percentOfPath += percentOfPathMultiplier;
                    xOffset += xOffsetStepIncrement;
                    yOffset += yOffsetStepIncrement;
                    zOffset += stepSize;
                    if (percentOfPath > this.pathCutEnd)
                        done = true;
                }
                else done = true;

                if (done && viewerMode)
                {
                    // add the top faces to the viewerFaces list here
                    Coord faceNormal = newLayer.faceNormal;
                    ViewerFace newViewerFace = new ViewerFace();
                    newViewerFace.primFaceNumber = 0;
                    int numFaces = newLayer.faces.Count;
                    List<Face> faces = newLayer.faces;

                    for (int i = 0; i < numFaces; i++)
                    {
                        Face face = faces[i];
                        newViewerFace.v1 = newLayer.coords[face.v1 - coordsLen];
                        newViewerFace.v2 = newLayer.coords[face.v2 - coordsLen];
                        newViewerFace.v3 = newLayer.coords[face.v3 - coordsLen];

                        newViewerFace.coordIndex1 = face.v1 - coordsLen;
                        newViewerFace.coordIndex2 = face.v2 - coordsLen;
                        newViewerFace.coordIndex3 = face.v3 - coordsLen;

                        newViewerFace.n1 = faceNormal;
                        newViewerFace.n2 = faceNormal;
                        newViewerFace.n3 = faceNormal;

                        newViewerFace.uv1 = newLayer.faceUVs[face.v1 - coordsLen];
                        newViewerFace.uv2 = newLayer.faceUVs[face.v2 - coordsLen];
                        newViewerFace.uv3 = newLayer.faceUVs[face.v3 - coordsLen];

                        this.viewerFaces.Add(newViewerFace);
                    }
                }
            }
        }
Example #9
0
        /// <summary>
        /// Extrude a profile into a circular path prim mesh. Used for prim types torus, tube, and ring.
        /// </summary>
        public void ExtrudeCircular()
        {
            this.coords = new List<Coord>();
            this.faces = new List<Face>();

            if (this.viewerMode)
            {
                this.viewerFaces = new List<ViewerFace>();
                this.calcVertexNormals = true;
            }

            if (this.calcVertexNormals)
                this.normals = new List<Coord>();

            int step = 0;
            int steps = 24;

            normalsProcessed = false;

            float twistBegin = this.twistBegin / 360.0f * twoPi;
            float twistEnd = this.twistEnd / 360.0f * twoPi;
            float twistTotal = twistEnd - twistBegin;

            // if the profile has a lot of twist, add more layers otherwise the layers may overlap
            // and the resulting mesh may be quite inaccurate. This method is arbitrary and doesn't
            // accurately match the viewer
            float twistTotalAbs = Math.Abs(twistTotal);
            if (twistTotalAbs > 0.01f)
            {
                if (twistTotalAbs > Math.PI * 1.5f)
                    steps *= 2;
                if (twistTotalAbs > Math.PI * 3.0f)
                    steps *= 2;
            }

            float yPathScale = this.holeSizeY * 0.5f;
            float pathLength = this.pathCutEnd - this.pathCutBegin;
            float totalSkew = this.skew * 2.0f * pathLength;
            float skewStart = this.pathCutBegin * 2.0f * this.skew - this.skew;
            float xOffsetTopShearXFactor = this.topShearX * (0.25f + 0.5f * (0.5f - this.holeSizeY));
            float yShearCompensation = 1.0f + Math.Abs(this.topShearY) * 0.25f;

            // It's not quite clear what pushY (Y top shear) does, but subtracting it from the start and end
            // angles appears to approximate it's effects on path cut. Likewise, adding it to the angle used
            // to calculate the sine for generating the path radius appears to approximate it's effects there
            // too, but there are some subtle differences in the radius which are noticeable as the prim size
            // increases and it may affect megaprims quite a bit. The effect of the Y top shear parameter on
            // the meshes generated with this technique appear nearly identical in shape to the same prims when
            // displayed by the viewer.

            float startAngle = (twoPi * this.pathCutBegin * this.revolutions) - this.topShearY * 0.9f;
            float endAngle = (twoPi * this.pathCutEnd * this.revolutions) - this.topShearY * 0.9f;
            float stepSize = twoPi / this.stepsPerRevolution;

            step = (int)(startAngle / stepSize);
            int firstStep = step;
            float angle = startAngle;
            float hollow = this.hollow;

            // sanity checks
            float initialProfileRot = 0.0f;
            if (this.sides == 3)
            {
                initialProfileRot = (float)Math.PI;
                if (this.hollowSides == 4)
                {
                    if (hollow > 0.7f)
                        hollow = 0.7f;
                    hollow *= 0.707f;
                }
                else hollow *= 0.5f;
            }
            else if (this.sides == 4)
            {
                initialProfileRot = 0.25f * (float)Math.PI;
                if (this.hollowSides != 4)
                    hollow *= 0.707f;
            }
            else if (this.sides > 4)
            {
                initialProfileRot = (float)Math.PI;
                if (this.hollowSides == 4)
                {
                    if (hollow > 0.7f)
                        hollow = 0.7f;
                    hollow /= 0.7f;
                }
            }

            bool needEndFaces = false;
            if (this.pathCutBegin != 0.0f || this.pathCutEnd != 1.0f)
                needEndFaces = true;
            else if (this.taperX != 0.0f || this.taperY != 0.0f)
                needEndFaces = true;
            else if (this.skew != 0.0f)
                needEndFaces = true;
            else if (twistTotal != 0.0f)
                needEndFaces = true;
            else if (this.radius != 0.0f)
                needEndFaces = true;

            Profile profile = new Profile(this.sides, this.profileStart, this.profileEnd, hollow, this.hollowSides, needEndFaces, calcVertexNormals);
            this.errorMessage = profile.errorMessage;

            this.numPrimFaces = profile.numPrimFaces;

            int cut1Vert = -1;
            int cut2Vert = -1;
            if (hasProfileCut)
            {
                cut1Vert = hasHollow ? profile.coords.Count - 1 : 0;
                cut2Vert = hasHollow ? profile.numOuterVerts - 1 : profile.numOuterVerts;
            }

            if (initialProfileRot != 0.0f)
            {
                profile.AddRot(new Quat(new Coord(0.0f, 0.0f, 1.0f), initialProfileRot));
                if (viewerMode)
                    profile.MakeFaceUVs();
            }

            Coord lastCutNormal1 = new Coord();
            Coord lastCutNormal2 = new Coord();
            float lastV = 1.0f;

            bool done = false;
            while (!done) // loop through the length of the path and add the layers
            {
                bool isEndLayer = false;
                if (angle <= startAngle + .01f || angle >= endAngle - .01f)
                    isEndLayer = true;

                Profile newLayer = profile.Copy();

                float xProfileScale = (1.0f - Math.Abs(this.skew)) * this.holeSizeX;
                float yProfileScale = this.holeSizeY;

                float percentOfPath = angle / (twoPi * this.revolutions);
                float percentOfAngles = (angle - startAngle) / (endAngle - startAngle);

                if (this.taperX > 0.01f)
                    xProfileScale *= 1.0f - percentOfPath * this.taperX;
                else if (this.taperX < -0.01f)
                    xProfileScale *= 1.0f + (1.0f - percentOfPath) * this.taperX;

                if (this.taperY > 0.01f)
                    yProfileScale *= 1.0f - percentOfPath * this.taperY;
                else if (this.taperY < -0.01f)
                    yProfileScale *= 1.0f + (1.0f - percentOfPath) * this.taperY;

                if (xProfileScale != 1.0f || yProfileScale != 1.0f)
                    newLayer.Scale(xProfileScale, yProfileScale);

                float radiusScale = 1.0f;
                if (this.radius > 0.001f)
                    radiusScale = 1.0f - this.radius * percentOfPath;
                else if (this.radius < 0.001f)
                    radiusScale = 1.0f + this.radius * (1.0f - percentOfPath);

                float twist = twistBegin + twistTotal * percentOfPath;

                float xOffset = 0.5f * (skewStart + totalSkew * percentOfAngles);
                xOffset += (float)Math.Sin(angle) * xOffsetTopShearXFactor;

                float yOffset = yShearCompensation * (float)Math.Cos(angle) * (0.5f - yPathScale) * radiusScale;

                float zOffset = (float)Math.Sin(angle + this.topShearY) * (0.5f - yPathScale) * radiusScale;

                // next apply twist rotation to the profile layer
                if (twistTotal != 0.0f || twistBegin != 0.0f)
                    newLayer.AddRot(new Quat(new Coord(0.0f, 0.0f, 1.0f), twist));

                // now orient the rotation of the profile layer relative to it's position on the path
                // adding taperY to the angle used to generate the quat appears to approximate the viewer
                newLayer.AddRot(new Quat(new Coord(1.0f, 0.0f, 0.0f), angle + this.topShearY));
                newLayer.AddPos(xOffset, yOffset, zOffset);

                if (isEndLayer && angle <= startAngle + .01f)
                {
                    newLayer.FlipNormals();

                    // add the top faces to the viewerFaces list here
                    if (this.viewerMode && needEndFaces)
                    {
                        Coord faceNormal = newLayer.faceNormal;
                        ViewerFace newViewerFace = new ViewerFace();
                        newViewerFace.primFaceNumber = 0;
                        foreach (Face face in newLayer.faces)
                        {
                            newViewerFace.v1 = newLayer.coords[face.v1];
                            newViewerFace.v2 = newLayer.coords[face.v2];
                            newViewerFace.v3 = newLayer.coords[face.v3];

                            newViewerFace.coordIndex1 = face.v1;
                            newViewerFace.coordIndex2 = face.v2;
                            newViewerFace.coordIndex3 = face.v3;

                            newViewerFace.n1 = faceNormal;
                            newViewerFace.n2 = faceNormal;
                            newViewerFace.n3 = faceNormal;

                            newViewerFace.uv1 = newLayer.faceUVs[face.v1];
                            newViewerFace.uv2 = newLayer.faceUVs[face.v2];
                            newViewerFace.uv3 = newLayer.faceUVs[face.v3];

                            this.viewerFaces.Add(newViewerFace);
                        }
                    }
                }

                // append the layer and fill in the sides

                int coordsLen = this.coords.Count;
                newLayer.AddValue2FaceVertexIndices(coordsLen);

                this.coords.AddRange(newLayer.coords);

                if (this.calcVertexNormals)
                {
                    newLayer.AddValue2FaceNormalIndices(this.normals.Count);
                    this.normals.AddRange(newLayer.vertexNormals);
                }

                if (isEndLayer)
                    this.faces.AddRange(newLayer.faces);

                // fill faces between layers

                int numVerts = newLayer.coords.Count;
                Face newFace = new Face();
                if (step > firstStep)
                {
                    int startVert = coordsLen + 1;
                    int endVert = this.coords.Count;

                    if (sides < 5 || this.hasProfileCut || hollow > 0.0f)
                        startVert--;

                    for (int i = startVert; i < endVert; i++)
                    {
                        int iNext = i + 1;
                        if (i == endVert - 1)
                            iNext = startVert;

                        int whichVert = i - startVert;

                        newFace.v1 = i;
                        newFace.v2 = i - numVerts;
                        newFace.v3 = iNext - numVerts;
                        this.faces.Add(newFace);

                        newFace.v2 = iNext - numVerts;
                        newFace.v3 = iNext;
                        this.faces.Add(newFace);

                        if (this.viewerMode)
                        {
                            int primFaceNumber = profile.faceNumbers[whichVert];
                            if (!needEndFaces)
                                primFaceNumber -= 1;

                            // add the side faces to the list of viewerFaces here
                            ViewerFace newViewerFace1 = new ViewerFace(primFaceNumber);
                            ViewerFace newViewerFace2 = new ViewerFace(primFaceNumber);
                            float u1 = newLayer.us[whichVert];
                            float u2 = 1.0f;
                            if (whichVert < newLayer.us.Count - 1)
                                u2 = newLayer.us[whichVert + 1];

                            if (whichVert == cut1Vert || whichVert == cut2Vert)
                            {
                                u1 = 0.0f;
                                u2 = 1.0f;
                            }
                            else if (sides < 5)
                            { // boxes and prisms have one texture face per side of the prim, so the U values have to be scaled
                                // to reflect the entire texture width
                                u1 *= sides;
                                u2 *= sides;
                                u2 -= (int)u1;
                                u1 -= (int)u1;
                                if (u2 < 0.1f)
                                    u2 = 1.0f;

                                //newViewerFace2.primFaceNumber = newViewerFace1.primFaceNumber = whichVert + 1;
                            }

                            newViewerFace1.uv1.U = u1;
                            newViewerFace1.uv2.U = u1;
                            newViewerFace1.uv3.U = u2;

                            newViewerFace1.uv1.V = 1.0f - percentOfPath;
                            newViewerFace1.uv2.V = lastV;
                            newViewerFace1.uv3.V = lastV;

                            newViewerFace2.uv1.U = u1;
                            newViewerFace2.uv2.U = u2;
                            newViewerFace2.uv3.U = u2;

                            newViewerFace2.uv1.V = 1.0f - percentOfPath;
                            newViewerFace2.uv2.V = lastV;
                            newViewerFace2.uv3.V = 1.0f - percentOfPath;

                            newViewerFace1.v1 = this.coords[i];
                            newViewerFace1.v2 = this.coords[i - numVerts];
                            newViewerFace1.v3 = this.coords[iNext - numVerts];

                            newViewerFace2.v1 = this.coords[i];
                            newViewerFace2.v2 = this.coords[iNext - numVerts];
                            newViewerFace2.v3 = this.coords[iNext];

                            newViewerFace1.coordIndex1 = i;
                            newViewerFace1.coordIndex2 = i - numVerts;
                            newViewerFace1.coordIndex3 = iNext - numVerts;

                            newViewerFace2.coordIndex1 = i;
                            newViewerFace2.coordIndex2 = iNext - numVerts;
                            newViewerFace2.coordIndex3 = iNext;

                            // profile cut faces
                            if (whichVert == cut1Vert)
                            {
                                newViewerFace1.n1 = newLayer.cutNormal1;
                                newViewerFace1.n2 = newViewerFace1.n3 = lastCutNormal1;

                                newViewerFace2.n1 = newViewerFace2.n3 = newLayer.cutNormal1;
                                newViewerFace2.n2 = lastCutNormal1;
                            }
                            else if (whichVert == cut2Vert)
                            {
                                newViewerFace1.n1 = newLayer.cutNormal2;
                                newViewerFace1.n2 = newViewerFace1.n3 = lastCutNormal2;

                                newViewerFace2.n1 = newViewerFace2.n3 = newLayer.cutNormal2;
                                newViewerFace2.n2 = lastCutNormal2;
                            }
                            else // periphery faces
                            {
                                if (sides < 5 && whichVert < newLayer.numOuterVerts)
                                {
                                    newViewerFace1.n1 = this.normals[i];
                                    newViewerFace1.n2 = this.normals[i - numVerts];
                                    newViewerFace1.n3 = this.normals[i - numVerts];

                                    newViewerFace2.n1 = this.normals[i];
                                    newViewerFace2.n2 = this.normals[i - numVerts];
                                    newViewerFace2.n3 = this.normals[i];
                                }
                                else if (hollowSides < 5 && whichVert >= newLayer.numOuterVerts)
                                {
                                    newViewerFace1.n1 = this.normals[iNext];
                                    newViewerFace1.n2 = this.normals[iNext - numVerts];
                                    newViewerFace1.n3 = this.normals[iNext - numVerts];

                                    newViewerFace2.n1 = this.normals[iNext];
                                    newViewerFace2.n2 = this.normals[iNext - numVerts];
                                    newViewerFace2.n3 = this.normals[iNext];
                                }
                                else
                                {
                                    newViewerFace1.n1 = this.normals[i];
                                    newViewerFace1.n2 = this.normals[i - numVerts];
                                    newViewerFace1.n3 = this.normals[iNext - numVerts];

                                    newViewerFace2.n1 = this.normals[i];
                                    newViewerFace2.n2 = this.normals[iNext - numVerts];
                                    newViewerFace2.n3 = this.normals[iNext];
                                }
                            }

                            //newViewerFace1.primFaceNumber = newViewerFace2.primFaceNumber = newLayer.faceNumbers[whichVert];
                            this.viewerFaces.Add(newViewerFace1);
                            this.viewerFaces.Add(newViewerFace2);

                        }
                    }
                }

                lastCutNormal1 = newLayer.cutNormal1;
                lastCutNormal2 = newLayer.cutNormal2;
                lastV = 1.0f - percentOfPath;

                // calculate terms for next iteration
                // calculate the angle for the next iteration of the loop

                if (angle >= endAngle - 0.01)
                    done = true;
                else
                {
                    step += 1;
                    angle = stepSize * step;
                    if (angle > endAngle)
                        angle = endAngle;
                }

                if (done && viewerMode && needEndFaces)
                {
                    // add the bottom faces to the viewerFaces list here
                    Coord faceNormal = newLayer.faceNormal;
                    ViewerFace newViewerFace = new ViewerFace();
                    //newViewerFace.primFaceNumber = newLayer.bottomFaceNumber + 1;
                    newViewerFace.primFaceNumber = newLayer.bottomFaceNumber;
                    foreach (Face face in newLayer.faces)
                    {
                        newViewerFace.v1 = newLayer.coords[face.v1 - coordsLen];
                        newViewerFace.v2 = newLayer.coords[face.v2 - coordsLen];
                        newViewerFace.v3 = newLayer.coords[face.v3 - coordsLen];

                        newViewerFace.coordIndex1 = face.v1 - coordsLen;
                        newViewerFace.coordIndex2 = face.v2 - coordsLen;
                        newViewerFace.coordIndex3 = face.v3 - coordsLen;

                        newViewerFace.n1 = faceNormal;
                        newViewerFace.n2 = faceNormal;
                        newViewerFace.n3 = faceNormal;

                        newViewerFace.uv1 = newLayer.faceUVs[face.v1 - coordsLen];
                        newViewerFace.uv2 = newLayer.faceUVs[face.v2 - coordsLen];
                        newViewerFace.uv3 = newLayer.faceUVs[face.v3 - coordsLen];

                        this.viewerFaces.Add(newViewerFace);
                    }
                }
            }
        }
Example #10
0
        public Profile(int sides, float profileStart, float profileEnd, float hollow, int hollowSides, bool hasProfileCut, bool createFaces)
        {
            const float halfSqr2 = 0.7071067811866f;
            
            this.coords = new List<Coord>();
            this.faces = new List<Face>();

            List<Coord> hollowCoords = new List<Coord>();

            bool hasHollow = (hollow > 0.0f);

            AngleList angles = new AngleList();
            AngleList hollowAngles = new AngleList();

            float xScale = 0.5f;
            float yScale = 0.5f;
            if (sides == 4)  // corners of a square are sqrt(2) from center
            {
                xScale = halfSqr2;
                yScale = halfSqr2;
            }

            float startAngle = profileStart * twoPi;
            float stopAngle = profileEnd * twoPi;

            try { angles.makeAngles(sides, startAngle, stopAngle,hasProfileCut); }
            catch (Exception ex)
            {

                errorMessage = "makeAngles failed: Exception: " + ex.ToString()
                + "\nsides: " + sides.ToString() + " startAngle: " + startAngle.ToString() + " stopAngle: " + stopAngle.ToString();

                return;
            }

            this.numOuterVerts = angles.angles.Count;

            Angle angle;
            Coord newVert = new Coord();

            // flag to create as few triangles as possible for 3 or 4 side profile
            bool simpleFace = (sides < 5 && !hasHollow && !hasProfileCut);

            if (hasHollow)
            {
                if (sides == hollowSides)
                    hollowAngles = angles;
                else
                {
                    try { hollowAngles.makeAngles(hollowSides, startAngle, stopAngle, hasProfileCut); }
                    catch (Exception ex)
                    {
                        errorMessage = "makeAngles failed: Exception: " + ex.ToString()
                        + "\nsides: " + sides.ToString() + " startAngle: " + startAngle.ToString() + " stopAngle: " + stopAngle.ToString();

                        return;
                    }

                    int numHollowAngles = hollowAngles.angles.Count;
                    for (int i = 0; i < numHollowAngles; i++)
                    {
                        angle = hollowAngles.angles[i];
                        newVert.X = hollow * xScale * angle.X;
                        newVert.Y = hollow * yScale * angle.Y;
                        newVert.Z = 0.0f;

                        hollowCoords.Add(newVert);
                    }
                }
                this.numHollowVerts = hollowAngles.angles.Count;
            }
            else if (!simpleFace)
            {
                Coord center = new Coord(0.0f, 0.0f, 0.0f);
                this.coords.Add(center);
            }

            int numAngles = angles.angles.Count;
            bool hollowsame = (hasHollow && hollowSides == sides);

            for (int i = 0; i < numAngles; i++)
            {
                angle = angles.angles[i];
                newVert.X = angle.X * xScale;
                newVert.Y = angle.Y * yScale;
                newVert.Z = 0.0f;
                this.coords.Add(newVert);
                if (hollowsame)
                {
                    newVert.X *= hollow;
                    newVert.Y *= hollow;
                    hollowCoords.Add(newVert);
                }
            }

            if (hasHollow)
            {
                hollowCoords.Reverse();
                this.coords.AddRange(hollowCoords);

                if (createFaces)
                {
                    int numTotalVerts = this.numOuterVerts + this.numHollowVerts;

                    if (this.numOuterVerts == this.numHollowVerts)
                    {
                        Face newFace = new Face();

                        for (int coordIndex = 0; coordIndex < this.numOuterVerts - 1; coordIndex++)
                        {
                            newFace.v1 = coordIndex;
                            newFace.v2 = coordIndex + 1;
                            newFace.v3 = numTotalVerts - coordIndex - 1;
                            this.faces.Add(newFace);

                            newFace.v1 = coordIndex + 1;
                            newFace.v2 = numTotalVerts - coordIndex - 2;
                            newFace.v3 = numTotalVerts - coordIndex - 1;
                            this.faces.Add(newFace);
                        }
                        if (!hasProfileCut)
                        {
                            newFace.v1 = this.numOuterVerts - 1;
                            newFace.v2 = 0;
                            newFace.v3 = this.numOuterVerts;
                            this.faces.Add(newFace);

                            newFace.v1 = 0;
                            newFace.v2 = numTotalVerts - 1;
                            newFace.v3 = this.numOuterVerts;
                            this.faces.Add(newFace);
                        }
                    }
                    else if (this.numOuterVerts < this.numHollowVerts)
                    {
                        Face newFace = new Face();
                        int j = 0; // j is the index for outer vertices
                        int i;
                        int maxJ = this.numOuterVerts - 1;
                        float curHollowAngle = 0;
                        for (i = 0; i < this.numHollowVerts; i++) // i is the index for inner vertices
                        {
                            curHollowAngle = hollowAngles.angles[i].angle;
                            if (j < maxJ)
                            {
                                if (angles.angles[j + 1].angle - curHollowAngle < curHollowAngle - angles.angles[j].angle + 0.000001f)
                                {
                                    newFace.v1 = numTotalVerts - i - 1;
                                    newFace.v2 = j;
                                    newFace.v3 = j + 1;
                                    this.faces.Add(newFace);
                                    j++;
                                }
                            }
                            else
                            {
                                if (1.0f - curHollowAngle < curHollowAngle - angles.angles[j].angle + 0.000001f)
                                    break;
                            }

                            newFace.v1 = j;
                            newFace.v2 = numTotalVerts - i - 2;
                            newFace.v3 = numTotalVerts - i - 1;

                            this.faces.Add(newFace);
                        }

                        if (!hasProfileCut)
                        {
                            if (i == this.numHollowVerts)
                            {
                                newFace.v1 = numTotalVerts - this.numHollowVerts;
                                newFace.v2 = maxJ;
                                newFace.v3 = 0;

                                this.faces.Add(newFace);
                            }
                            else
                            {
                                if (1.0f - curHollowAngle < curHollowAngle - angles.angles[maxJ].angle + 0.000001f)
                                {
                                    newFace.v1 = numTotalVerts - i - 1;
                                    newFace.v2 = maxJ;
                                    newFace.v3 = 0;

                                    this.faces.Add(newFace);
                                }

                                for (; i < this.numHollowVerts - 1; i++)
                                {
                                    newFace.v1 = 0;
                                    newFace.v2 = numTotalVerts - i - 2;
                                    newFace.v3 = numTotalVerts - i - 1;

                                    this.faces.Add(newFace);
                                }
                            }

                            newFace.v1 = 0;
                            newFace.v2 = numTotalVerts - this.numHollowVerts;
                            newFace.v3 = numTotalVerts - 1;
                            this.faces.Add(newFace);
                        }
                    }
                    else // numHollowVerts < numOuterVerts
                    {
                        Face newFace = new Face();
                        int j = 0; // j is the index for inner vertices
                        int maxJ = this.numHollowVerts - 1;
                        for (int i = 0; i < this.numOuterVerts; i++)
                        {
                            if (j < maxJ)
                                if (hollowAngles.angles[j + 1].angle - angles.angles[i].angle < angles.angles[i].angle - hollowAngles.angles[j].angle + 0.000001f)
                                {
                                    newFace.v1 = i;
                                    newFace.v2 = numTotalVerts - j - 2;
                                    newFace.v3 = numTotalVerts - j - 1;

                                    this.faces.Add(newFace);
                                    j += 1;
                                }

                            newFace.v1 = numTotalVerts - j - 1;
                            newFace.v2 = i;
                            newFace.v3 = i + 1;

                            this.faces.Add(newFace);
                        }

                        if (!hasProfileCut)
                        {
                            int i = this.numOuterVerts - 1;

                            if (hollowAngles.angles[0].angle - angles.angles[i].angle < angles.angles[i].angle - hollowAngles.angles[maxJ].angle + 0.000001f)
                            {
                                newFace.v1 = 0;
                                newFace.v2 = numTotalVerts - maxJ - 1;
                                newFace.v3 = numTotalVerts - 1;

                                this.faces.Add(newFace);
                            }

                            newFace.v1 = numTotalVerts - maxJ - 1;
                            newFace.v2 = i;
                            newFace.v3 = 0;

                            this.faces.Add(newFace);
                        }
                    }
                }
                
            }

            else if (createFaces)
            {
                if (simpleFace)
                {
                    if (sides == 3)
                        this.faces.Add(new Face(0, 1, 2));
                    else if (sides == 4)
                    {
                        this.faces.Add(new Face(0, 1, 2));
                        this.faces.Add(new Face(0, 2, 3));
                    }
                }
                else
                {
                    for (int i = 1; i < numAngles ; i++)
                    {
                        Face newFace = new Face();
                        newFace.v1 = 0;
                        newFace.v2 = i;
                        newFace.v3 = i + 1;
                        this.faces.Add(newFace);
                    }
                    if (!hasProfileCut)
                    {
                        Face newFace = new Face();
                        newFace.v1 = 0;
                        newFace.v2 = numAngles;
                        newFace.v3 = 1;
                        this.faces.Add(newFace);
                    }
                }
            }


            hollowCoords = null;
        }
Example #11
0
        private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, Vector3 size, float lod,
                                              ulong key)
        {
            PrimMesh primMesh;
            SculptMesh sculptMesh;

            List<Coord> coords = new List<Coord>();
            List<Face> faces = new List<Face>();

            Image idata = null;
            string decodedSculptFileName = "";

            if (primShape.SculptEntry)
            {
                if (((SculptType) primShape.SculptType) == SculptType.Mesh)
                {
                    if (!useMeshiesPhysicsMesh)
                        return null;

                    MainConsole.Instance.Debug("[MESH]: experimental mesh proxy generation");

                    OSD meshOsd = null;

                    if (primShape.SculptData == null || primShape.SculptData.Length <= 0)
                    {
                        MainConsole.Instance.Error("[MESH]: asset data is zero length");
                        return null;
                    }

                    long start = 0;
                    using (MemoryStream data = new MemoryStream(primShape.SculptData))
                    {
                        try
                        {
                            meshOsd = OSDParser.DeserializeLLSDBinary(data);
                        }
                        catch (Exception e)
                        {
                            MainConsole.Instance.Error("[MESH]: Exception deserializing mesh asset header:" + e);
                        }
                        start = data.Position;
                    }

                    if (meshOsd is OSDMap)
                    {
                        OSDMap map = (OSDMap) meshOsd;
                        OSDMap physicsParms = new OSDMap();

                        if (map.ContainsKey("physics_cached"))
                        {
                            OSD cachedMeshMap = map["physics_cached"]; // cached data from Aurora
                            Mesh cachedMesh = new Mesh(key);
                            cachedMesh.Deserialize(cachedMeshMap);
                            cachedMesh.WasCached = true;
                            return cachedMesh;//Return here, we found all of the info right here
                        }
                        if (map.ContainsKey("physics_shape"))
                            physicsParms = (OSDMap)map["physics_shape"]; // old asset format
                        if (physicsParms.Count == 0 && map.ContainsKey("physics_mesh"))
                            physicsParms = (OSDMap)map["physics_mesh"]; // new asset format
                        if (physicsParms.Count == 0 && map.ContainsKey("physics_convex"))
                            // convex hull format, which we can't read, so instead
                            // read the highest lod that exists, and use it instead
                            physicsParms = (OSDMap)map["high_lod"]; 

                        int physOffset = physicsParms["offset"].AsInteger() + (int) start;
                        int physSize = physicsParms["size"].AsInteger();

                        if (physOffset < 0 || physSize == 0)
                            return null; // no mesh data in asset

                        OSD decodedMeshOsd = new OSD();
                        byte[] meshBytes = new byte[physSize];
                        Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize);
                        try
                        {
                            using (MemoryStream inMs = new MemoryStream(meshBytes))
                            {
                                using (MemoryStream outMs = new MemoryStream())
                                {
                                    using (ZOutputStream zOut = new ZOutputStream(outMs))
                                    {
                                        byte[] readBuffer = new byte[2048];
                                        int readLen = 0;
                                        while ((readLen = inMs.Read(readBuffer, 0, readBuffer.Length)) > 0)
                                        {
                                            zOut.Write(readBuffer, 0, readLen);
                                        }
                                        zOut.Flush();
                                        outMs.Seek(0, SeekOrigin.Begin);

                                        byte[] decompressedBuf = outMs.GetBuffer();

                                        decodedMeshOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            MainConsole.Instance.Error("[MESH]: exception decoding physical mesh: " + e);
                            return null;
                        }

                        OSDArray decodedMeshOsdArray = null;

                        // physics_shape is an array of OSDMaps, one for each submesh
                        if (decodedMeshOsd is OSDArray)
                        {
                            decodedMeshOsdArray = (OSDArray) decodedMeshOsd;
                            foreach (OSD subMeshOsd in decodedMeshOsdArray)
                            {
                                if (subMeshOsd is OSDMap)
                                {
                                    OSDMap subMeshMap = (OSDMap) subMeshOsd;

                                    // As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level
                                    // of Detail Blocks (maps) contain just a NoGeometry key to signal there is no
                                    // geometry for this submesh.
                                    if (subMeshMap.ContainsKey("NoGeometry") && (subMeshMap["NoGeometry"]))
                                        continue;

                                    Vector3 posMax = new Vector3(0.5f, 0.5f, 0.5f);
                                    Vector3 posMin = new Vector3(-0.5f, -0.5f, -0.5f);
                                    if (subMeshMap.ContainsKey("PositionDomain"))//Optional, so leave the max and min values otherwise
                                    {
                                        posMax = ((OSDMap)subMeshMap["PositionDomain"])["Max"].AsVector3();
                                        posMin = ((OSDMap)subMeshMap["PositionDomain"])["Min"].AsVector3();
                                    }
                                    ushort faceIndexOffset = (ushort) coords.Count;

                                    byte[] posBytes = subMeshMap["Position"].AsBinary();
                                    for (int i = 0; i < posBytes.Length; i += 6)
                                    {
                                        ushort uX = Utils.BytesToUInt16(posBytes, i);
                                        ushort uY = Utils.BytesToUInt16(posBytes, i + 2);
                                        ushort uZ = Utils.BytesToUInt16(posBytes, i + 4);

                                        Coord c = new Coord(
                                            Utils.UInt16ToFloat(uX, posMin.X, posMax.X)*size.X,
                                            Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y)*size.Y,
                                            Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z)*size.Z);

                                        coords.Add(c);
                                    }

                                    byte[] triangleBytes = subMeshMap["TriangleList"].AsBinary();
                                    for (int i = 0; i < triangleBytes.Length; i += 6)
                                    {
                                        ushort v1 = (ushort) (Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset);
                                        ushort v2 =
                                            (ushort) (Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset);
                                        ushort v3 =
                                            (ushort) (Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset);
                                        Face f = new Face(v1, v2, v3);
                                        faces.Add(f);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero)
                    {
                        decodedSculptFileName = Path.Combine(decodedSculptMapPath,
                                                             "smap_" + primShape.SculptTexture.ToString());
                        try
                        {
                            if (File.Exists(decodedSculptFileName))
                            {
                                idata = Image.FromFile(decodedSculptFileName);
                            }
                        }
                        catch (Exception e)
                        {
                            MainConsole.Instance.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e);
                        }
                        //if (idata != null)
                        //    MainConsole.Instance.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString());
                    }

                    if (idata == null)
                    {
                        if (primShape.SculptData == null || primShape.SculptData.Length == 0)
                            return null;

                        try
                        {
                            ManagedImage unusedData;
                            OpenJPEG.DecodeToImage(primShape.SculptData, out unusedData, out idata);
                            unusedData = null;

                            if (cacheSculptMaps && idata != null)
                            {
                                try
                                {
                                    idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp);
                                }
                                catch (Exception e)
                                {
                                    MainConsole.Instance.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " +
                                                e);
                                }
                            }
                        }
                        catch (DllNotFoundException)
                        {
                            MainConsole.Instance.Error(
                                "[PHYSICS]: OpenJpeg is not installed correctly on this system. Physics Proxy generation failed.  Often times this is because of an old version of GLIBC.  You must have version 2.4 or above!");
                            return null;
                        }
                        catch (IndexOutOfRangeException)
                        {
                            MainConsole.Instance.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
                            return null;
                        }
                        catch (Exception ex)
                        {
                            MainConsole.Instance.Error(
                                "[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " +
                                ex);
                            return null;
                        }
                    }

                    SculptMesh.SculptType sculptType;
                    switch ((SculptType) primShape.SculptType)
                    {
                        case SculptType.Cylinder:
                            sculptType = SculptMesh.SculptType.cylinder;
                            break;
                        case SculptType.Plane:
                            sculptType = SculptMesh.SculptType.plane;
                            break;
                        case SculptType.Torus:
                            sculptType = SculptMesh.SculptType.torus;
                            break;
                        case SculptType.Sphere:
                            sculptType = SculptMesh.SculptType.sphere;
                            break;
                        default:
                            sculptType = SculptMesh.SculptType.plane;
                            break;
                    }

                    bool mirror = ((primShape.SculptType & 128) != 0);
                    bool invert = ((primShape.SculptType & 64) != 0);

                    if (idata == null)
                        return null;

                    sculptMesh = new SculptMesh((Bitmap) idata, sculptType, (int) lod, false, mirror, invert);

                    idata.Dispose();
                    idata = null;

                    sculptMesh.DumpRaw(baseDir, primName, "primMesh");

                    sculptMesh.Scale(size.X, size.Y, size.Z);

                    coords = sculptMesh.coords;
                    faces = sculptMesh.faces;
                }
            }
            else
            {
                float pathShearX = primShape.PathShearX < 128
                                       ? primShape.PathShearX*0.01f
                                       : (primShape.PathShearX - 256)*0.01f;
                float pathShearY = primShape.PathShearY < 128
                                       ? primShape.PathShearY*0.01f
                                       : (primShape.PathShearY - 256)*0.01f;
                float pathBegin = primShape.PathBegin*2.0e-5f;
                float pathEnd = 1.0f - primShape.PathEnd*2.0e-5f;
                float pathScaleX = (primShape.PathScaleX - 100)*0.01f;
                float pathScaleY = (primShape.PathScaleY - 100)*0.01f;

                float profileBegin = primShape.ProfileBegin*2.0e-5f;
                float profileEnd = 1.0f - primShape.ProfileEnd*2.0e-5f;
                float profileHollow = primShape.ProfileHollow*2.0e-5f;
                if (profileHollow > 0.95f)
                {
                    if (profileHollow > 0.99f)
                        profileHollow = 0.99f;
                    float sizeX = primShape.Scale.X - (primShape.Scale.X*profileHollow);
                    if (sizeX < 0.1f) //If its > 0.1, its fine to mesh at the small hollow
                        profileHollow = 0.95f + (sizeX/2); //Scale the rest by how large the size of the prim is
                }

                int sides = 4;
                if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.EquilateralTriangle)
                    sides = 3;
                else if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.Circle)
                    sides = 24;
                else if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.HalfCircle)
                {
                    // half circle, prim is a sphere
                    sides = 24;

                    profileBegin = 0.5f*profileBegin + 0.5f;
                    profileEnd = 0.5f*profileEnd + 0.5f;
                }

                int hollowSides = sides;
                if (primShape.HollowShape == HollowShape.Circle)
                    hollowSides = 24;
                else if (primShape.HollowShape == HollowShape.Square)
                    hollowSides = 4;
                else if (primShape.HollowShape == HollowShape.Triangle)
                    hollowSides = 3;

                primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);

                if (primMesh.errorMessage != null)
                    if (primMesh.errorMessage.Length > 0)
                        MainConsole.Instance.Error("[ERROR] " + primMesh.errorMessage);

                primMesh.topShearX = pathShearX;
                primMesh.topShearY = pathShearY;
                primMesh.pathCutBegin = pathBegin;
                primMesh.pathCutEnd = pathEnd;

                if (primShape.PathCurve == (byte) Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
                {
                    primMesh.twistBegin = primShape.PathTwistBegin*18/10;
                    primMesh.twistEnd = primShape.PathTwist*18/10;
                    primMesh.taperX = pathScaleX;
                    primMesh.taperY = pathScaleY;

                    if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
                    {
                        ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
                        if (profileBegin < 0.0f) profileBegin = 0.0f;
                        if (profileEnd > 1.0f) profileEnd = 1.0f;
                    }
#if SPAM
                MainConsole.Instance.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
#endif
                    try
                    {
                        primMesh.Extrude(primShape.PathCurve == (byte) Extrusion.Straight
                                             ? PathType.Linear
                                             : PathType.Flexible);
                    }
                    catch (Exception ex)
                    {
                        ReportPrimError("Extrusion failure: exception: " + ex, primName, primMesh);
                        return null;
                    }
                }
                else
                {
                    primMesh.holeSizeX = (200 - primShape.PathScaleX)*0.01f;
                    primMesh.holeSizeY = (200 - primShape.PathScaleY)*0.01f;
                    primMesh.radius = 0.01f*primShape.PathRadiusOffset;
                    primMesh.revolutions = 1.0f + 0.015f*primShape.PathRevolutions;
                    primMesh.skew = 0.01f*primShape.PathSkew;
                    primMesh.twistBegin = primShape.PathTwistBegin*36/10;
                    primMesh.twistEnd = primShape.PathTwist*36/10;
                    primMesh.taperX = primShape.PathTaperX*0.01f;
                    primMesh.taperY = primShape.PathTaperY*0.01f;

                    if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
                    {
                        ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
                        if (profileBegin < 0.0f) profileBegin = 0.0f;
                        if (profileEnd > 1.0f) profileEnd = 1.0f;
                    }
#if SPAM
                MainConsole.Instance.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
#endif
                    try
                    {
                        primMesh.Extrude(PathType.Circular);
                    }
                    catch (Exception ex)
                    {
                        ReportPrimError("Extrusion failure: exception: " + ex, primName, primMesh);
                        return null;
                    }
                }

                primMesh.DumpRaw(baseDir, primName, "primMesh");

                primMesh.Scale(size.X, size.Y, size.Z);

                coords = primMesh.coords;
                faces = primMesh.faces;
                primMesh = null;
            }

            int numCoords = coords.Count;
            int numFaces = faces.Count;

            // Create the list of vertices
            List<Vertex> vertices = new List<Vertex>();
            for (int i = 0; i < numCoords; i++)
            {
                Coord c = coords[i];
                vertices.Add(new Vertex(c.X, c.Y, c.Z));
            }

            Mesh mesh = new Mesh(key);
            // Add the corresponding triangles to the mesh
            for (int i = 0; i < numFaces; i++)
            {
                Face f = faces[i];
                mesh.Add(new Triangle(vertices[f.v1], vertices[f.v2], vertices[f.v3]));
            }
            coords.Clear();
            faces.Clear();
            coords = null;
            faces = null;
            return mesh;
        }
Example #12
0
        /// <summary>
        /// Extrudes a profile along a path.
        /// </summary>
        public void Extrude(PathType pathType)
        {
            bool needEndFaces = false;

            this.coords = new List<Coord>();
            this.faces = new List<Face>();

            int steps = 1;

            float length = this.pathCutEnd - this.pathCutBegin;

            this.hasProfileCut = this.profileEnd - this.profileStart < 0.9999f;

            this.hasHollow = (this.hollow > 0.001f);

            float twistBegin = this.twistBegin / 360.0f * twoPi;
            float twistEnd = this.twistEnd / 360.0f * twoPi;
            float twistTotal = twistEnd - twistBegin;
            float twistTotalAbs = Math.Abs(twistTotal);
            if (twistTotalAbs > 0.01f)
                steps += (int)(twistTotalAbs * 3.66); //  dahlia's magic number

            float hollow = this.hollow;

            if (pathType == PathType.Circular)
            {
                needEndFaces = false;
                if (this.pathCutBegin != 0.0f || this.pathCutEnd != 1.0f)
                    needEndFaces = true;
                else if (this.taperX != 0.0f || this.taperY != 0.0f)
                    needEndFaces = true;
                else if (this.skew != 0.0f)
                    needEndFaces = true;
                else if (twistTotal != 0.0f)
                    needEndFaces = true;
                else if (this.radius != 0.0f)
                    needEndFaces = true;
            }
            else needEndFaces = true;

            // sanity checks
            float initialProfileRot = 0.0f;
            if (pathType == PathType.Circular)
            {
                if (this.sides == 3)
                {
                    initialProfileRot = (float)Math.PI;
                    if (this.hollowSides == 4)
                    {
                        if (hollow > 0.7f)
                            hollow = 0.7f;
                        hollow *= 0.707f;
                    }
                    else hollow *= 0.5f;
                }
                else if (this.sides == 4)
                {
                    initialProfileRot = 0.25f * (float)Math.PI;
                    if (this.hollowSides != 4)
                        hollow *= 0.707f;
                }
                else if (this.sides > 4)
                {
                    initialProfileRot = (float)Math.PI;
                    if (this.hollowSides == 4)
                    {
                        if (hollow > 0.7f)
                            hollow = 0.7f;
                        hollow /= 0.7f;
                    }
                }
            }
            else
            {
                if (this.sides == 3)
                {
                    if (this.hollowSides == 4)
                    {
                        if (hollow > 0.7f)
                            hollow = 0.7f;
                        hollow *= 0.707f;
                    }
                    else hollow *= 0.5f;
                }
                else if (this.sides == 4)
                {
                    initialProfileRot = 1.25f * (float)Math.PI;
                    if (this.hollowSides != 4)
                        hollow *= 0.707f;
                }
                else if (this.sides == 24 && this.hollowSides == 4)
                    hollow *= 1.414f;
            }

            Profile profile = new Profile(this.sides, this.profileStart, this.profileEnd, hollow, this.hollowSides, this.hasProfileCut,true);
            this.errorMessage = profile.errorMessage;

            this.numPrimFaces = profile.numPrimFaces;

            if (initialProfileRot != 0.0f)
            {
                profile.AddRot(new Quat(new Coord(0.0f, 0.0f, 1.0f), initialProfileRot));
            }

            float thisV = 0.0f;
            float lastV = 0.0f;

            Path path = new Path();
            path.twistBegin = twistBegin;
            path.twistEnd = twistEnd;
            path.topShearX = topShearX;
            path.topShearY = topShearY;
            path.pathCutBegin = pathCutBegin;
            path.pathCutEnd = pathCutEnd;
            path.dimpleBegin = dimpleBegin;
            path.dimpleEnd = dimpleEnd;
            path.skew = skew;
            path.holeSizeX = holeSizeX;
            path.holeSizeY = holeSizeY;
            path.taperX = taperX;
            path.taperY = taperY;
            path.radius = radius;
            path.revolutions = revolutions;
            path.stepsPerRevolution = stepsPerRevolution;

            path.Create(pathType, steps);
            
            int lastNode = path.pathNodes.Count -1;

            for (int nodeIndex = 0; nodeIndex < path.pathNodes.Count; nodeIndex++)
            {
                PathNode node = path.pathNodes[nodeIndex];
                Profile newLayer = profile.Copy();

                newLayer.Scale(node.xScale, node.yScale);
                newLayer.AddRot(node.rotation);
                newLayer.AddPos(node.position);

                if (needEndFaces && nodeIndex == 0)
                {
                    newLayer.FlipNormals();
                } // if (nodeIndex == 0)

                // append this layer

                int coordsLen = this.coords.Count;
                newLayer.AddValue2FaceVertexIndices(coordsLen);

                this.coords.AddRange(newLayer.coords);

                if (needEndFaces)
                {
                    if (nodeIndex == 0)
                        this.faces.AddRange(newLayer.faces);
                    else if (nodeIndex == lastNode)
                    {
                        if (node.xScale > 1e-6 && node.yScale > 1e-6)
                            this.faces.AddRange(newLayer.faces);
                    }
                }

                // fill faces between layers

                int numVerts = newLayer.coords.Count;
                Face newFace1 = new Face();
                Face newFace2 = new Face();

                thisV = 1.0f - node.percentOfPath;

                if (nodeIndex > 0)
                {
                    int startVert = coordsLen;
                    int endVert = this.coords.Count;
                    if (!this.hasProfileCut)
                    {
                        int i = startVert;
                        for (int l = 0; l < profile.numOuterVerts - 1; l++)
                        {
                            newFace1.v1 = i;
                            newFace1.v2 = i - numVerts;
                            newFace1.v3 = i + 1;
                            this.faces.Add(newFace1);

                            newFace2.v1 = i + 1;
                            newFace2.v2 = i - numVerts;
                            newFace2.v3 = i + 1 - numVerts;
                            this.faces.Add(newFace2);
                            i++;
                        }

                        newFace1.v1 = i;
                        newFace1.v2 = i - numVerts;
                        newFace1.v3 = startVert;
                        this.faces.Add(newFace1);

                        newFace2.v1 = startVert;
                        newFace2.v2 = i - numVerts;
                        newFace2.v3 = startVert - numVerts;
                        this.faces.Add(newFace2);

                        if (this.hasHollow)
                        {
                            startVert = ++i;
                            for (int l = 0; l < profile.numHollowVerts - 1; l++)
                            {
                                newFace1.v1 = i;
                                newFace1.v2 = i - numVerts;
                                newFace1.v3 = i + 1;
                                this.faces.Add(newFace1);

                                newFace2.v1 = i + 1;
                                newFace2.v2 = i - numVerts;
                                newFace2.v3 = i + 1 - numVerts;
                                this.faces.Add(newFace2);
                                i++;
                            }

                            newFace1.v1 = i;
                            newFace1.v2 = i - numVerts;
                            newFace1.v3 = startVert;
                            this.faces.Add(newFace1);

                            newFace2.v1 = startVert;
                            newFace2.v2 = i - numVerts;
                            newFace2.v3 = startVert - numVerts;
                            this.faces.Add(newFace2);
                        }


                    }
                    else
                    {
                        for (int i = startVert; i < endVert; i++)
                        {
                            int iNext = i + 1;
                            if (i == endVert - 1)
                                iNext = startVert;

                            newFace1.v1 = i;
                            newFace1.v2 = i - numVerts;
                            newFace1.v3 = iNext;
                            this.faces.Add(newFace1);

                            newFace2.v1 = iNext;
                            newFace2.v2 = i - numVerts;
                            newFace2.v3 = iNext - numVerts;
                            this.faces.Add(newFace2);

                        }
                    }
                }

                lastV = thisV;

            } // for (int nodeIndex = 0; nodeIndex < path.pathNodes.Count; nodeIndex++)

        }
Example #13
0
        private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
        {
            PrimMesh primMesh;
            PrimMesher.SculptMesh sculptMesh;

            List<Coord> coords = new List<Coord>();
            List<Face> faces = new List<Face>();

            Image idata = null;
            string decodedSculptFileName = "";

            if (primShape.SculptEntry)
            {
                if (((OpenMetaverse.SculptType)primShape.SculptType) == SculptType.Mesh)
                {
                    if (!useMeshiesPhysicsMesh)
                        return null;

                    m_log.Debug("[MESH]: experimental mesh proxy generation");

                    OSD meshOsd;

                    if (primShape.SculptData.Length <= 0)
                    {
                        m_log.Error("[MESH]: asset data is zero length");
                        return null;
                    }

                    long start = 0;
                    using (MemoryStream data = new MemoryStream(primShape.SculptData))
                    {
                        meshOsd = (OSDMap)OSDParser.DeserializeLLSDBinary(data);
                        start = data.Position;
                    }

                    if (meshOsd is OSDMap)
                    {
                        OSDMap map = (OSDMap)meshOsd;
                        OSDMap physicsParms = (OSDMap)map["physics_shape"];
                        int physOffset = physicsParms["offset"].AsInteger() + (int)start;
                        int physSize = physicsParms["size"].AsInteger();

                        if (physOffset < 0 || physSize == 0)
                            return null; // no mesh data in asset

                        OSD decodedMeshOsd = new OSD();
                        byte[] meshBytes = new byte[physSize];
                        System.Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize);
                        byte[] decompressed = new byte[physSize * 5];
                        try
                        {
                            using (MemoryStream inMs = new MemoryStream(meshBytes))
                            {
                                using (MemoryStream outMs = new MemoryStream())
                                {
                                    using (ZOutputStream zOut = new ZOutputStream(outMs))
                                    {
                                        byte[] readBuffer = new byte[2048];
                                        int readLen = 0;
                                        while ((readLen = inMs.Read(readBuffer, 0, readBuffer.Length)) > 0)
                                        {
                                            zOut.Write(readBuffer, 0, readLen);
                                        }
                                        zOut.Flush();
                                        outMs.Seek(0, SeekOrigin.Begin);

                                        byte[] decompressedBuf = outMs.GetBuffer();

                                        decodedMeshOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            m_log.Error("[MESH]: exception decoding physical mesh: " + e.ToString());
                            return null;
                        }

                        OSDArray decodedMeshOsdArray = null;

                        // physics_shape is an array of OSDMaps, one for each submesh
                        if (decodedMeshOsd is OSDArray)
                        {
                            decodedMeshOsdArray = (OSDArray)decodedMeshOsd;
                            foreach (OSD subMeshOsd in decodedMeshOsdArray)
                            {
                                if (subMeshOsd is OSDMap)
                                {
                                    OSDMap subMeshMap = (OSDMap)subMeshOsd;

                                    OpenMetaverse.Vector3 posMax = ((OSDMap)subMeshMap["PositionDomain"])["Max"].AsVector3();
                                    OpenMetaverse.Vector3 posMin = ((OSDMap)subMeshMap["PositionDomain"])["Min"].AsVector3();
                                    ushort faceIndexOffset = (ushort)coords.Count;

                                    byte[] posBytes = subMeshMap["Position"].AsBinary();
                                    for (int i = 0; i < posBytes.Length; i += 6)
                                    {
                                        ushort uX = Utils.BytesToUInt16(posBytes, i);
                                        ushort uY = Utils.BytesToUInt16(posBytes, i + 2);
                                        ushort uZ = Utils.BytesToUInt16(posBytes, i + 4);

                                        Coord c = new Coord(
                                        Utils.UInt16ToFloat(uX, posMin.X, posMax.X) * size.X,
                                        Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y) * size.Y,
                                        Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z) * size.Z);

                                        coords.Add(c);
                                    }

                                    byte[] triangleBytes = subMeshMap["TriangleList"].AsBinary();
                                    for (int i = 0; i < triangleBytes.Length; i += 6)
                                    {
                                        ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset);
                                        ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset);
                                        ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset);
                                        Face f = new Face(v1, v2, v3);
                                        faces.Add(f);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero)
                    {
                        decodedSculptFileName = System.IO.Path.Combine(decodedSculptMapPath, "smap_" + primShape.SculptTexture.ToString());
                        try
                        {
                            if (File.Exists(decodedSculptFileName))
                            {
                                idata = Image.FromFile(decodedSculptFileName);
                            }
                        }
                        catch (Exception e)
                        {
                            m_log.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e.Message);

                        }
                        //if (idata != null)
                        //    m_log.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString());
                    }

                    if (idata == null)
                    {
                        if (primShape.SculptData == null || primShape.SculptData.Length == 0)
                            return null;

                        try
                        {
                            OpenMetaverse.Imaging.ManagedImage unusedData;
                            OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out unusedData, out idata);
                            unusedData = null;

                            //idata = CSJ2K.J2kImage.FromBytes(primShape.SculptData);

                            if (cacheSculptMaps && idata != null)
                            {
                                try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); }
                                catch (Exception e) { m_log.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " + e.Message); }
                            }
                        }
                        catch (DllNotFoundException)
                        {
                            m_log.Error("[PHYSICS]: OpenJpeg is not installed correctly on this system. Physics Proxy generation failed.  Often times this is because of an old version of GLIBC.  You must have version 2.4 or above!");
                            return null;
                        }
                        catch (IndexOutOfRangeException)
                        {
                            m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
                            return null;
                        }
                        catch (Exception ex)
                        {
                            m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message);
                            return null;
                        }
                    }

                    PrimMesher.SculptMesh.SculptType sculptType;
                    switch ((OpenMetaverse.SculptType)primShape.SculptType)
                    {
                        case OpenMetaverse.SculptType.Cylinder:
                            sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
                            break;
                        case OpenMetaverse.SculptType.Plane:
                            sculptType = PrimMesher.SculptMesh.SculptType.plane;
                            break;
                        case OpenMetaverse.SculptType.Torus:
                            sculptType = PrimMesher.SculptMesh.SculptType.torus;
                            break;
                        case OpenMetaverse.SculptType.Sphere:
                            sculptType = PrimMesher.SculptMesh.SculptType.sphere;
                            break;
                        default:
                            sculptType = PrimMesher.SculptMesh.SculptType.plane;
                            break;
                    }

                    bool mirror = ((primShape.SculptType & 128) != 0);
                    bool invert = ((primShape.SculptType & 64) != 0);

                    sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert);
                    
                    idata.Dispose();

                    sculptMesh.DumpRaw(baseDir, primName, "primMesh");

                    sculptMesh.Scale(size.X, size.Y, size.Z);

                    coords = sculptMesh.coords;
                    faces = sculptMesh.faces;
                }
            }
            else
            {
                float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
                float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
                float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
                float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
                float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
                float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;

                float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
                float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
                float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
                if (profileHollow > 0.95f)
                    profileHollow = 0.95f;

                int sides = 4;
                if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
                    sides = 3;
                else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
                    sides = 24;
                else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
                { // half circle, prim is a sphere
                    sides = 24;

                    profileBegin = 0.5f * profileBegin + 0.5f;
                    profileEnd = 0.5f * profileEnd + 0.5f;

                }

                int hollowSides = sides;
                if (primShape.HollowShape == HollowShape.Circle)
                    hollowSides = 24;
                else if (primShape.HollowShape == HollowShape.Square)
                    hollowSides = 4;
                else if (primShape.HollowShape == HollowShape.Triangle)
                    hollowSides = 3;

                primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);

                if (primMesh.errorMessage != null)
                    if (primMesh.errorMessage.Length > 0)
                        m_log.Error("[ERROR] " + primMesh.errorMessage);

                primMesh.topShearX = pathShearX;
                primMesh.topShearY = pathShearY;
                primMesh.pathCutBegin = pathBegin;
                primMesh.pathCutEnd = pathEnd;

                if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
                {
                    primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10;
                    primMesh.twistEnd = primShape.PathTwist * 18 / 10;
                    primMesh.taperX = pathScaleX;
                    primMesh.taperY = pathScaleY;

                    if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
                    {
                        ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
                        if (profileBegin < 0.0f) profileBegin = 0.0f;
                        if (profileEnd > 1.0f) profileEnd = 1.0f;
                    }
#if SPAM
                m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
#endif
                    try
                    {
                        primMesh.ExtrudeLinear();
                    }
                    catch (Exception ex)
                    {
                        ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
                        return null;
                    }
                }
                else
                {
                    primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
                    primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
                    primMesh.radius = 0.01f * primShape.PathRadiusOffset;
                    primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
                    primMesh.skew = 0.01f * primShape.PathSkew;
                    primMesh.twistBegin = primShape.PathTwistBegin * 36 / 10;
                    primMesh.twistEnd = primShape.PathTwist * 36 / 10;
                    primMesh.taperX = primShape.PathTaperX * 0.01f;
                    primMesh.taperY = primShape.PathTaperY * 0.01f;

                    if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
                    {
                        ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
                        if (profileBegin < 0.0f) profileBegin = 0.0f;
                        if (profileEnd > 1.0f) profileEnd = 1.0f;
                    }
#if SPAM
                m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
#endif
                    try
                    {
                        primMesh.ExtrudeCircular();
                    }
                    catch (Exception ex)
                    {
                        ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
                        return null;
                    }
                }

                primMesh.DumpRaw(baseDir, primName, "primMesh");

                primMesh.Scale(size.X, size.Y, size.Z);

                coords = primMesh.coords;
                faces = primMesh.faces;
            }

            // Remove the reference to any JPEG2000 sculpt data so it can be GCed
            primShape.SculptData = Utils.EmptyBytes;

            int numCoords = coords.Count;
            int numFaces = faces.Count;

            // Create the list of vertices
            List<Vertex> vertices = new List<Vertex>();
            for (int i = 0; i < numCoords; i++)
            {
                Coord c = coords[i];
                vertices.Add(new Vertex(c.X, c.Y, c.Z));
            }

            Mesh mesh = new Mesh();
            // Add the corresponding triangles to the mesh
            for (int i = 0; i < numFaces; i++)
            {
                Face f = faces[i];
                mesh.Add(new Triangle(vertices[f.v1], vertices[f.v2], vertices[f.v3]));
            }
            return mesh;
        }
Example #14
0
        /// <summary>
        /// Add a submesh to an existing list of coords and faces.
        /// </summary>
        /// <param name="subMeshData"></param>
        /// <param name="size">Size of entire object</param>
        /// <param name="coords"></param>
        /// <param name="faces"></param>
        private void AddSubMesh(OSDMap subMeshData, Vector3 size, List<Coord> coords, List<Face> faces)
        {
            //                                    Console.WriteLine("subMeshMap for {0} - {1}", primName, Util.GetFormattedXml((OSD)subMeshMap));

            // As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level
            // of Detail Blocks (maps) contain just a NoGeometry key to signal there is no
            // geometry for this submesh.
            if (subMeshData.ContainsKey("NoGeometry") && ((OSDBoolean)subMeshData["NoGeometry"]))
                return;

            OpenMetaverse.Vector3 posMax = ((OSDMap)subMeshData["PositionDomain"])["Max"].AsVector3();
            OpenMetaverse.Vector3 posMin = ((OSDMap)subMeshData["PositionDomain"])["Min"].AsVector3();
            ushort faceIndexOffset = (ushort)coords.Count;

            byte[] posBytes = subMeshData["Position"].AsBinary();
            ExtractCoordsFrom16BitPositions(size, coords, ref posMax, ref posMin, posBytes, 0, int.MaxValue);

            byte[] triangleBytes = subMeshData["TriangleList"].AsBinary();
            for (int i = 0; i < triangleBytes.Length; i += 6)
            {
                ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset);
                ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset);
                ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset);
                Face f = new Face(v1, v2, v3);
                faces.Add(f);
            }
        }
Example #15
0
        void _SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror, bool invert)
        {
            coords = new List<Coord>();
            faces = new List<Face>();
            normals = new List<Coord>();
            uvs = new List<UVCoord>();

            sculptType = (SculptType)(((int)sculptType) & 0x07);

            if (mirror)
                if (sculptType == SculptType.plane)
                    invert = !invert;

            float sourceScaleFactor = (float)(lod) / (float)Math.Sqrt(sculptBitmap.Width * sculptBitmap.Height);

            int scale = (int)(1.0f / sourceScaleFactor);
            if (scale < 1) scale = 1;

            List<List<Coord>> rows = bitmap2Coords(sculptBitmap, scale, mirror);

            viewerFaces = new List<ViewerFace>();

            int width = sculptBitmap.Width / scale;
            // int height = sculptBitmap.Height / scale;

            int p1, p2, p3, p4;

            int imageX, imageY;

            if (sculptType != SculptType.plane)
            {
                for (int rowNdx = 0; rowNdx < rows.Count; rowNdx++)
                    rows[rowNdx].Add(rows[rowNdx][0]);
            }

            Coord topPole = rows[0][width / 2];
            Coord bottomPole = rows[rows.Count - 1][width / 2];

            if (sculptType == SculptType.sphere)
            {
                int count = rows[0].Count;
                List<Coord> topPoleRow = new List<Coord>(count);
                List<Coord> bottomPoleRow = new List<Coord>(count);

                for (int i = 0; i < count; i++)
                {
                    topPoleRow.Add(topPole);
                    bottomPoleRow.Add(bottomPole);
                }
                rows.Insert(0, topPoleRow);
                rows.Add(bottomPoleRow);
            }
            else if (sculptType == SculptType.torus)
                rows.Add(rows[0]);

            int coordsDown = rows.Count;
            int coordsAcross = rows[0].Count;

            float widthUnit = 1.0f / (coordsAcross - 1);
            float heightUnit = 1.0f / (coordsDown - 1);

            for (imageY = 0; imageY < coordsDown; imageY++)
            {
                int rowOffset = imageY * coordsAcross;

                for (imageX = 0; imageX < coordsAcross; imageX++)
                {
                    /*
                    *   p1-----p2
                    *   | \ f2 |
                    *   |   \  |
                    *   | f1  \|
                    *   p3-----p4
                    */

                    p4 = rowOffset + imageX;
                    p3 = p4 - 1;

                    p2 = p4 - coordsAcross;
                    p1 = p3 - coordsAcross;

                    this.coords.Add(rows[imageY][imageX]);
                    if (viewerMode)
                    {
                        this.normals.Add(new Coord());
                        this.uvs.Add(new UVCoord(widthUnit * imageX, heightUnit * imageY));
                    }

                    if (imageY > 0 && imageX > 0)
                    {
                        Face f1, f2;

                        if (viewerMode)
                        {
                            if (invert)
                            {
                                f1 = new Face(p1, p4, p3, p1, p4, p3);
                                f1.uv1 = p1;
                                f1.uv2 = p4;
                                f1.uv3 = p3;

                                f2 = new Face(p1, p2, p4, p1, p2, p4);
                                f2.uv1 = p1;
                                f2.uv2 = p2;
                                f2.uv3 = p4;
                            }
                            else
                            {
                                f1 = new Face(p1, p3, p4, p1, p3, p4);
                                f1.uv1 = p1;
                                f1.uv2 = p3;
                                f1.uv3 = p4;

                                f2 = new Face(p1, p4, p2, p1, p4, p2);
                                f2.uv1 = p1;
                                f2.uv2 = p4;
                                f2.uv3 = p2;
                            }
                        }
                        else
                        {
                            if (invert)
                            {
                                f1 = new Face(p1, p4, p3);
                                f2 = new Face(p1, p2, p4);
                            }
                            else
                            {
                                f1 = new Face(p1, p3, p4);
                                f2 = new Face(p1, p4, p2);
                            }
                        }

                        this.faces.Add(f1);
                        this.faces.Add(f2);
                    }
                }
            }

            if (viewerMode)
                calcVertexNormals(sculptType, coordsAcross, coordsDown);
        }
Example #16
0
        private void _SculptMesh(List<List<Coord>> rows, SculptType sculptType, bool invert)
        {
            coords = new List<Coord>();
            faces = new List<Face>();

            sculptType = (SculptType)(((int)sculptType) & 0x07);

            int width = rows[0].Count;

            int p1, p2, p3, p4;

            int imageX, imageY;

            if (sculptType != SculptType.plane)
            {
                if (rows.Count % 2 == 0)
                {
                    for (int rowNdx = 0; rowNdx < rows.Count; rowNdx++)
                        rows[rowNdx].Add(rows[rowNdx][0]);
                }
                else
                {
                    int lastIndex = rows[0].Count - 1;

                    for (int i = 0; i < rows.Count; i++)
                        rows[i][0] = rows[i][lastIndex];
                }
            }

            Coord topPole = rows[0][width / 2];
            Coord bottomPole = rows[rows.Count - 1][width / 2];

            if (sculptType == SculptType.sphere)
            {
                if (rows.Count % 2 == 0)
                {
                    int count = rows[0].Count;
                    List<Coord> topPoleRow = new List<Coord>(count);
                    List<Coord> bottomPoleRow = new List<Coord>(count);

                    for (int i = 0; i < count; i++)
                    {
                        topPoleRow.Add(topPole);
                        bottomPoleRow.Add(bottomPole);
                    }
                    rows.Insert(0, topPoleRow);
                    rows.Add(bottomPoleRow);
                }
                else
                {
                    int count = rows[0].Count;

                    List<Coord> topPoleRow = rows[0];
                    List<Coord> bottomPoleRow = rows[rows.Count - 1];

                    for (int i = 0; i < count; i++)
                    {
                        topPoleRow[i] = topPole;
                        bottomPoleRow[i] = bottomPole;
                    }
                }
            }

            if (sculptType == SculptType.torus)
                rows.Add(rows[0]);

            int coordsDown = rows.Count;
            int coordsAcross = rows[0].Count;

            float widthUnit = 1.0f / (coordsAcross - 1);
            float heightUnit = 1.0f / (coordsDown - 1);

            for (imageY = 0; imageY < coordsDown; imageY++)
            {
                int rowOffset = imageY * coordsAcross;

                for (imageX = 0; imageX < coordsAcross; imageX++)
                {
                    /*
                    *   p1-----p2
                    *   | \ f2 |
                    *   |   \  |
                    *   | f1  \|
                    *   p3-----p4
                    */

                    p4 = rowOffset + imageX;
                    p3 = p4 - 1;

                    p2 = p4 - coordsAcross;
                    p1 = p3 - coordsAcross;

                    this.coords.Add(rows[imageY][imageX]);

                    if (imageY > 0 && imageX > 0)
                    {
                        Face f1, f2;

                            if (invert)
                            {
                                f1 = new Face(p1, p4, p3);
                                f2 = new Face(p1, p2, p4);
                            }
                            else
                            {
                                f1 = new Face(p1, p3, p4);
                                f2 = new Face(p1, p4, p2);
                            }

                        this.faces.Add(f1);
                        this.faces.Add(f2);
                    }
                }
            }
        }