コード例 #1
0
ファイル: EdgeDrawer.cs プロジェクト: gviaud/OS-unity-5
    // dessine une edge d'une epaisseur thickness en appliquant les transformations
    // de planMatrix
    public static void Draw(Edge2 edge, Matrix4x4 planMatrix, int thickness = 10, 
		float offsetWidth=0, float offsetHeight=0)
    {
        Matrix4x4 matrix = GUI.matrix;

        Vector2 nextPt = edge.GetNextPoint2 ();
        nextPt.Set(nextPt.x+offsetWidth, nextPt.y+offsetHeight);
        nextPt = planMatrix.MultiplyPoint (nextPt);

        Vector2 prevPt = edge.GetPrevPoint2 ();
        prevPt.Set(prevPt.x+offsetWidth, prevPt.y+offsetHeight);
        prevPt = planMatrix.MultiplyPoint (prevPt);

        float angle = Vector2.Angle(nextPt - prevPt, Vector2.right);

        if (prevPt.y > nextPt.y)
        {
            angle = -angle;
        }

        GUIUtility.RotateAroundPivot (angle, prevPt);

        GUI.DrawTexture(new Rect (prevPt.x, prevPt.y - thickness / 2 ,
            (nextPt - prevPt).magnitude, thickness), SOLID_EDGE_TEXTURE);

        GUI.matrix = matrix;
    }
コード例 #2
0
ファイル: MeshGenerator.cs プロジェクト: nyuvlg/4DExperiments
    public void createCylinder(float radius, float height, int slices, GameObject go, Matrix4x4 matrix)
    {
        Mesh cylinderMesh = new Mesh();
        vertices = new Vector3[(slices+1) * 4];
        Vector3[] cylPoints1 = createCylinderPoints(radius, height, slices, true);
        Vector3[] cylPoints2 = createCylinderPoints(radius, height, slices, false);
        for (int i = 0; i <cylPoints1.Length; i++) {
            vertices[i] = cylPoints1[i];
        }
        for (int k = 0; k < cylPoints2.Length; k++) {
            vertices[k + cylPoints1.Length] = cylPoints2[k];
        }

        createCylinderNormals(vertices, radius);
        for (int j = 0; j < vertices.Length; j++) {
            vertices[j] = matrix.MultiplyPoint(vertices[j]);
            normals[j] = matrix.MultiplyPoint(normals[j]);
        }

        trianglesIndex = 0;
        createCylinderTriangles(slices+1);

        cylinderMesh.vertices = vertices;
        cylinderMesh.triangles = triangles;
        cylinderMesh.normals = normals;
        cylinderMesh.uv = uvs;

        MeshFilter filter = (MeshFilter)go.GetComponent("MeshFilter");
        filter.mesh = cylinderMesh;
    }
コード例 #3
0
ファイル: MegaFFDEditor.cs プロジェクト: schonstal/madness
    public void DrawGizmos(MegaFFD ffd, Matrix4x4 tm)
    {
        Handles.color = Color.red;

        int pc = ffd.GridSize();

        for ( int  i = 0; i < pc; i++ )
        {
            for ( int j = 0; j < pc; j++ )
            {
                for ( int k = 0; k < pc; k++ )
                {
                    pp3[0] = tm.MultiplyPoint(ffd.GetPoint(i, j, k) + ffd.bcenter);

                    if ( i < pc - 1 )
                    {
                        pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i + 1, j, k) + ffd.bcenter);
                        Handles.DrawLine(pp3[0], pp3[1]);
                    }

                    if ( j < pc - 1 )
                    {
                        pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j + 1, k) + ffd.bcenter);
                        Handles.DrawLine(pp3[0], pp3[1]);
                    }

                    if ( k < pc - 1 )
                    {
                        pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j, k + 1) + ffd.bcenter);
                        Handles.DrawLine(pp3[0], pp3[1]);
                    }
                }
            }
        }
    }
コード例 #4
0
ファイル: MeshBuilder.cs プロジェクト: mANDROID99/IaS
 public void AddQuad(bool reverse, Matrix4x4 quadTransform, bool merge)
 {
     this.AddTriangleStrip(reverse,
       new Vertex[]{
         VertAutoNormal(quadTransform.MultiplyPoint(new Vector3(0.5f, 0.5f, 0)), new Vector2(1,1), merge),
         VertAutoNormal(quadTransform.MultiplyPoint(new Vector3(0.5f, -0.5f, 0)), new Vector2(1,0), merge),
         VertAutoNormal(quadTransform.MultiplyPoint(new Vector3(-0.5f, 0.5f, 0)), new Vector2(0,1), merge),
         VertAutoNormal(quadTransform.MultiplyPoint(new Vector3(-0.5f, -0.5f, 0)), new Vector2(0,0), merge),
     });
 }
コード例 #5
0
ファイル: LeftArm.cs プロジェクト: guiklink/Unity3d_Twig
    void drawAngleLine(Matrix4x4 refMatrix, Color color)
    {
        Vector3 start = Vector3.zero;
        Vector3 end = new Vector3 (-5, 0, 0);

        Vector3 startInWorldCoord = refMatrix.MultiplyPoint (start);
        Vector3 endInWorldCoord = refMatrix.MultiplyPoint (end);

        Debug.DrawLine (startInWorldCoord, endInWorldCoord, color);
    }
コード例 #6
0
ファイル: Face.cs プロジェクト: icegbq/csg-unity
	public void Transform( Matrix4x4 inMatrix )
	{		
		for( int i = 0; i < vertices.Length; ++i )
		{
			vertices[i] = inMatrix.MultiplyPoint( vertices[i] );
		}
	}
コード例 #7
0
ファイル: BoxEditor.cs プロジェクト: BenjaminMoore/JPhysics
 private void AdjustMidpointHandleColor(Vector3 localPos, Vector3 localTangent, Vector3 localBinormal, Matrix4x4 transform, float alphaFactor)
 {
     float num;
     Vector3 vector = transform.MultiplyPoint(localPos);
     Vector3 lhs = transform.MultiplyVector(localTangent);
     Vector3 rhs = transform.MultiplyVector(localBinormal);
     Vector3 normalized = Vector3.Cross(lhs, rhs).normalized;
     if (Camera.current.isOrthoGraphic)
     {
         num = Vector3.Dot(-Camera.current.transform.forward, normalized);
     }
     else
     {
         Vector3 vector6 = Camera.current.transform.position - vector;
         num = Vector3.Dot(vector6.normalized, normalized);
     }
     if (num < -0.0001f)
     {
         alphaFactor *= 0.2f;
     }
     if (alphaFactor < 1f)
     {
         Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, Handles.color.a * alphaFactor);
     }
 }
コード例 #8
0
 public void MapsTo(Matrix4x4 trMatrix)
 {
     for (int i = 0; i < length; i++ )
     {
         points[i] = trMatrix.MultiplyPoint(points[i]);
     }
 }
コード例 #9
0
ファイル: UtilitiesHandles.cs プロジェクト: Bohofx/ICS
 // UnityEditor.HandleUtility
 /// <summary>
 ///   <para>Map a mouse drag onto a movement along a line in 3D space.</para>
 /// </summary>
 /// <param name="src">The source point of the drag.</param>
 /// <param name="dest">The destination point of the drag.</param>
 /// <param name="srcPosition">The 3D position the dragged object had at src ray.</param>
 /// <param name="constraintDir">3D direction of constrained movement.</param>
 /// <returns>
 ///   <para>The distance travelled along constraintDir.</para>
 /// </returns>
 public static float CalcLineTranslation(Vector2 src, Vector2 dest, Vector3 srcPosition, Vector3 constraintDir, Matrix4x4 handleMatrix)
 {
     srcPosition = handleMatrix.MultiplyPoint(srcPosition);
     constraintDir = handleMatrix.MultiplyVector(constraintDir);
     float num = 1f;
     Vector3 forward = Camera.main.transform.forward;
     if(Vector3.Dot(constraintDir, forward) < 0f)
     {
         num = -1f;
     }
     Vector3 vector = constraintDir;
     vector.y = -vector.y;
     Camera current = Camera.main;
     Vector2 vector2 = PixelsToPoints(current.WorldToScreenPoint(srcPosition));
     Vector2 vector3 = PixelsToPoints(current.WorldToScreenPoint(srcPosition + constraintDir * num));
     Vector2 x = dest;
     Vector2 x2 = src;
     if(vector2 == vector3)
     {
         return 0f;
     }
     //x.y = -x.y;
     //x2.y = -x2.y;
     float parametrization = GetParametrization(x2, vector2, vector3);
     float parametrization2 = GetParametrization(x, vector2, vector3);
     return (parametrization2 - parametrization) * num;
 }
コード例 #10
0
ファイル: GizmoDraw.cs プロジェクト: alerdenisov/ADAPT
    /// <summary>
    /// Draws a gizmo cylinder with the given TRS matrix and color
    /// </summary>
    /// <param name="trs"></param>
    /// <param name="color"></param>
    public static void DrawCylinder(Matrix4x4 trs, Color color)
    {
        if (cylVerts == null || cylTris == null)
        {
            GameObject cyl = GameObject.CreatePrimitive(
                PrimitiveType.Cylinder);
            MeshFilter filter = cyl.GetComponent<MeshFilter>();
            cylVerts = filter.sharedMesh.vertices;
            cylTris = filter.sharedMesh.triangles;
            GameObject.DestroyImmediate(cyl);
        }

        Vector3[] verts = new Vector3[cylVerts.Length];
        for (int i = 0; i < cylVerts.Length; i++)
            verts[i] = trs.MultiplyPoint(cylVerts[i]);

        Gizmos.color = color;
        for (int i = 0; i < cylTris.Length / 3; i++)
        {
            int j = i * 3;
            Gizmos.DrawLine(verts[cylTris[j]],
                verts[cylTris[j + 1]]);
            Gizmos.DrawLine(verts[cylTris[j + 1]],
                verts[cylTris[j + 2]]);
            Gizmos.DrawLine(verts[cylTris[j + 2]],
                verts[cylTris[j]]);
        }
    }
コード例 #11
0
ファイル: MenuMoverBehavior.cs プロジェクト: VentorLee/unity
	void Start () {
		_menuRoots = GameObject.FindGameObjectsWithTag("MenuRoot");
		_menus = GameObject.FindGameObjectsWithTag("Menu");
		_currentState = MoverState.PASSIVE;

		//Account for differing aspect ratios
		Vector2 screenSize = new Vector2(Screen.width, Screen.height);
		Vector2 screenDiff = _layoutOriginalAspectRatio -  screenSize;

		if(Mathf.Abs(screenDiff.x) < Mathf.Abs(screenDiff.y)) {
			float amt = _layoutOriginalAspectRatio.x / screenSize.x;
			screenSize *= amt;
		}
		else {
			float amt = _layoutOriginalAspectRatio.y / screenSize.y;
			screenSize *= amt;
		}

		float horizRatio = screenSize.x / (float)_layoutOriginalAspectRatio.x;
		float vertRatio = screenSize.y / (float)_layoutOriginalAspectRatio.y;

		_guiMatrix = Matrix4x4.TRS (new Vector3(0, 0, 0), Quaternion.identity, new Vector3 (horizRatio, vertRatio, 1));

		foreach(GameObject menu in _menus)
		{
			MenuBehavior menuScript = menu.GetComponent(typeof(MenuBehavior)) as MenuBehavior;
			menuScript.baseLocation = _guiMatrix.MultiplyPoint(menuScript.baseLocation);
		}
	}
コード例 #12
0
ファイル: BoxEditor.cs プロジェクト: BenjaminMoore/JPhysics
 private void AdjustEdgeHandleColor(Vector3 handlePos, Vector3 slideDir1, Vector3 slideDir2, Matrix4x4 transform, float alphaFactor)
 {
     bool flag;
     Vector3 inPoint = transform.MultiplyPoint(handlePos);
     Vector3 normalized = transform.MultiplyVector(slideDir1).normalized;
     Vector3 rhs = transform.MultiplyVector(slideDir2).normalized;
     if (Camera.current.isOrthoGraphic)
     {
         flag = (Vector3.Dot(-Camera.current.transform.forward, normalized) < 0f) && (Vector3.Dot(-Camera.current.transform.forward, rhs) < 0f);
     }
     else
     {
         Plane plane = new Plane(normalized, inPoint);
         Plane plane2 = new Plane(rhs, inPoint);
         flag = !plane.GetSide(Camera.current.transform.position) && !plane2.GetSide(Camera.current.transform.position);
     }
     if (flag)
     {
         alphaFactor *= 0.2f;
     }
     if (alphaFactor < 1f)
     {
         Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, Handles.color.a * alphaFactor);
     }
 }
コード例 #13
0
    public Vector3 DirectionTo3DGridPosition(Vector3 observer, Vector3 direction, float yPlane)
    {
        direction = direction.normalized;

        Matrix4x4 mat = new Matrix4x4();

        float multiple = (yPlane - observer.y) / direction.y;

        mat.SetTRS(direction * multiple, Quaternion.identity, Vector3.one);

        Vector3 newPoint = mat.MultiplyPoint(observer);

        return GetNearest3DGridPoint(newPoint);
    }
コード例 #14
0
    public Vector3[] SurfaceGrid()
    {
        var width = Mathf.CeilToInt((float)Screen.width / pitchPix);
        var height = Mathf.CeilToInt((float)screenHeight / pitchPix);
        var widthPlusOne = width + 1;
        var heightPlusOne = height + 1;
        var vertexCount = widthPlusOne * heightPlusOne;
        if (vertexCount > VERTEX_LIMIT)
            return null;

        _triangleInvalidated = (width != _prevWidth || height != _prevHeight);
        if (_triangleInvalidated) {
            _mesh.Clear();
            _prevWidth = width;
            _prevHeight = height;
            _vertices = new Vector3[vertexCount];
        }

        var m = new Matrix4x4();
        m.SetTRS(new Vector3(-1f, -1f, 0f), Quaternion.identity, new Vector3(2f / Screen.width, 2f / Screen.height, 1f));
        m = targetCamera.cameraToWorldMatrix * targetCamera.projectionMatrix.inverse * m;
        var v = new Vector4(0f, 0f, 0f, 1f);
        for (var y = 0; y <= height; y++) {
            for (var x = 0; x <= width; x++) {
                var i = y * widthPlusOne + x;
                v.x = x * pitchPix;
                v.y = screenHeight - y * pitchPix;
                _vertices[i] = m.MultiplyPoint(v);
            }
        }

        if (_triangleInvalidated) {
            _triangles = new int[6 * width * height];
            var counter = 0;
            for (var y = 0; y < height; y++) {
                for (var x = 0; x < width; x++) {
                    var i = y * widthPlusOne + x;
                    _triangles[counter++] = i;
                    _triangles[counter++] = i + 1;
                    _triangles[counter++] = i + + widthPlusOne + 1;
                    _triangles[counter++] = i;
                    _triangles[counter++] = i + widthPlusOne + 1;
                    _triangles[counter++] = i + widthPlusOne;
                }
            }
        }

        return _vertices;
    }
コード例 #15
0
 static public int MultiplyPoint(IntPtr l)
 {
     try{
         UnityEngine.Matrix4x4 self = (UnityEngine.Matrix4x4)checkSelf(l);
         UnityEngine.Vector3   a1;
         checkType(l, 2, out a1);
         UnityEngine.Vector3 ret = self.MultiplyPoint(a1);
         pushValue(l, ret);
         return(1);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
コード例 #16
0
    private void UpdateCameraParentPose()
    {
        Interlocked.Exchange(ref updateCameraToWorldMatrix, _cameraToWorldMatrix);

        UnityEngine.Matrix4x4 cameraToWorldMatrix = ConvertFloatArrayToMatrix4x4(updateCameraToWorldMatrix);

        Transform locatableCameraTransform = controller.LocatableCameraRoot.transform;

        // Note: we can't just directly convert the matrix into the rotation/position that Unity expects.
        // We need to convert it. See https://forum.unity.com/threads/locatable-camera-in-unity.398803/
        Vector3    position = cameraToWorldMatrix.MultiplyPoint(Vector3.zero);
        Quaternion rotation = Quaternion.LookRotation(-cameraToWorldMatrix.GetColumn(2), cameraToWorldMatrix.GetColumn(1));

        locatableCameraTransform.position = position;
        locatableCameraTransform.rotation = rotation;
    }
コード例 #17
0
 static int MultiplyPoint(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         UnityEngine.Matrix4x4 obj  = (UnityEngine.Matrix4x4)ToLua.CheckObject(L, 1, typeof(UnityEngine.Matrix4x4));
         UnityEngine.Vector3   arg0 = ToLua.ToVector3(L, 2);
         UnityEngine.Vector3   o    = obj.MultiplyPoint(arg0);
         ToLua.Push(L, o);
         ToLua.SetBack(L, 1, obj);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
コード例 #18
0
ファイル: MeshUtils.cs プロジェクト: ttldtor/NoteCAD
    public static Solid ToSolid(this Mesh mesh, UnityEngine.Matrix4x4 tf)
    {
        var indices  = mesh.GetIndices(0);
        var polygons = new List <Polygon>();
        var mverts   = mesh.vertices;

        for (int i = 0; i < indices.Length / 3; i++)
        {
            var vertices = new List <Vertex>();
            for (int j = 0; j < 3; j++)
            {
                var v = mverts[indices[i * 3 + j]];
                v = tf.MultiplyPoint(v);
                vertices.Add(v.ToVertex());
            }
            polygons.Add(new Polygon(vertices, -1));
        }
        return(Solid.FromPolygons(polygons));
    }
コード例 #19
0
    // Function to apply transformation to 4th point/object
    void ApplyTransformation()
    {
        //Calculating Centroids from both coordinate system
        centroidA = (UnitytoAccord(CubeReg.transform.position) + UnitytoAccord(SphereReg.transform.position)
                     + UnitytoAccord(CylinderReg.transform.position)) / 3;
        centroidB = (UnitytoAccord(CubeTransformed.transform.position) + UnitytoAccord(SphereTransformed.transform.position)
                     + UnitytoAccord(CylinderTransformed.transform.position)) / 3;
        //Debug.Log("Centroid A is" + centroidA + " Centroid B is" + centroidB);

        // Calculating Covariance Matrix
        H = CovarianceMatrixStep(UnitytoAccord(CubeReg.transform.position) - centroidA, UnitytoAccord(CubeTransformed.transform.position) - centroidB)
            + CovarianceMatrixStep(UnitytoAccord(SphereReg.transform.position) - centroidA, UnitytoAccord(SphereTransformed.transform.position) - centroidB)
            + CovarianceMatrixStep(UnitytoAccord(CylinderReg.transform.position) - centroidA, UnitytoAccord(CylinderTransformed.transform.position) - centroidB);

        H.SVD(out U, out E, out V);
        R = V * U.Transpose();

        //special reflection case
        if (R.Determinant < 0)
        {
            V.V02 = (-V.V02);
            V.V12 = (-V.V12);
            V.V22 = (-V.V22);
            R     = V * U.Transpose();
            Debug.LogWarning("Reflection case");
        }

        Translation = NegativeMatrix(R) * centroidA + centroidB;
        //Debug.Log("Translation is" + Translation);
        TransformationMatrix = AccordToUnityMatrix(TransformationMatrix, R, Translation);
        //Debug.Log(TransformationMatrix);

        // Transformaiton Matrix for Unity
        TransformationMatrix.SetTRS(AccordtoUnity(Translation), Quaternion.LookRotation(TransformationMatrix.GetColumn(1),
                                                                                        TransformationMatrix.GetColumn(2)), UnityEngine.Vector3.one);

        // Applying Translation and rotation to 4th point/object
        TestObject.transform.position = TransformationMatrix.MultiplyPoint(InitPosition);
        TestObject.transform.rotation = Quaternion.LookRotation(TransformationMatrix.GetColumn(1), TransformationMatrix.GetColumn(2)) * InitQT;
    }
コード例 #20
0
        public void Transform(Matrix4x4 transform)
        {
            // Transform main polygon
            for (int i = 0; i < this.Count; i++)
            {
                this[i] = transform.MultiplyPoint(this[i]);
            }

            // Transform holes
            Vector2[] temp = null;
            if (_holes != null && _holes.Count > 0)
            {
                for (int i = 0; i < _holes.Count; i++)
                {
                    temp = _holes[i].ToArray();
                    for (int j = 0; j < temp.Length; j++)
                    {
                        temp[i] = transform.MultiplyPoint(temp[i]);
                    }

                    _holes[i] = new Vertices(temp);
                }
            }
        }
コード例 #21
0
 static void Copy(int vertexcount, Vector3[] src, Vector3[] dst, ref int offset, Matrix4x4 transform)
 {
     for (int i=0;i<src.Length;i++)
         dst[i+offset] = transform.MultiplyPoint(src[i]);
     offset += vertexcount;
 }
コード例 #22
0
ファイル: MeshCombiner.cs プロジェクト: TK-97/ICO_AGM_Asg02
	public void GetVertices (int vertexcount, Vector3[] sources, Vector3[] main, ref int offset, Matrix4x4 transform)
	{
		for (int i = 0;i < sources.Length;i++)
			main[i+offset] = transform.MultiplyPoint(sources[i]);
		offset += vertexcount;
	}
コード例 #23
0
ファイル: MeshUtils.cs プロジェクト: mmiscool/NoteCAD
    public static Solid CreateSolidRevolve(List <List <Entity> > entitiyLoops, float angle, float helixStep, Vector3 axis, Vector3 origin, float angleStep, UnityEngine.Matrix4x4 tf, IdPath feature)
    {
        var  ids      = new List <List <Id> >();
        var  polygons = Sketch.GetPolygons(entitiyLoops, ref ids);
        bool isHelix  = (Math.Abs(helixStep) > 1e-6);

        if (!isHelix && Mathf.Abs(angle) > 360f)
        {
            angle = Mathf.Sign(angle) * 360f;
        }
        bool inversed = angle < 0f;
        int  subdiv   = (int)Mathf.Ceil(Math.Abs(angle) / angleStep);
        var  drot     = UnityEngine.Matrix4x4.Translate(origin) * UnityEngine.Matrix4x4.Rotate(Quaternion.AngleAxis(angle / subdiv, axis)) * UnityEngine.Matrix4x4.Translate(-origin);

        Func <float, Vector3, Vector3> PointOn = (float a, Vector3 point) => {
            var ax  = axis;
            var axn = axis.normalized;
            var t   = a / 360.0f;
            var o   = origin;
            var prj = ExpVector.ProjectPointToLine(point, o, o + ax);
            var ra  = Mathf.Atan2(helixStep / 4.0f, (point - prj).magnitude);
            var res = ExpVector.RotateAround(point, point - prj, o, ra);
            res = ExpVector.RotateAround(res, ax, o, a * Mathf.PI / 180.0f);
            return(res + axn * t * helixStep);
        };

        var polys = new List <Polygon>();
        Func <Vector3, Vector3> TF = v => tf.MultiplyPoint(v);

        for (int pi = 0; pi < polygons.Count; pi++)
        {
            var p         = polygons[pi];
            var pid       = ids[pi];
            var pv        = new List <Vector3>(p);
            var triangles = Triangulation.Triangulate(pv);

            IdPath polyId  = feature.With(new Id(-1));
            bool   invComp = true;

            if (Math.Abs(Math.Abs(angle) - 360f) > 1e-6 || isHelix)
            {
                float a = 0f;
                for (int side = 0; side < 2; side++)
                {
                    for (int i = 0; i < triangles.Count / 3; i++)
                    {
                        var polygonVertices = new List <Vertex>();
                        for (int j = 0; j < 3; j++)
                        {
                            polygonVertices.Add(PointOn(a, TF(triangles[i * 3 + j])).ToVertex());
                        }
                        if (inversed == invComp)
                        {
                            polygonVertices.Reverse();
                        }
                        polys.Add(new Polygon(polygonVertices, polyId));
                    }
                    polyId  = feature.With(new Id(-2));
                    invComp = false;
                    a       = angle;
                }
            }

            Dictionary <Id, IdPath> paths = new Dictionary <Id, IdPath>();
            for (int i = 0; i < p.Count; i++)
            {
                float a  = 0f;
                float da = angle / subdiv;
                for (int j = 0; j < subdiv; j++)
                {
                    var polygonVertices = new List <Vertex>();
                    polygonVertices.Add(PointOn(a, TF(p[(i + 1) % p.Count])).ToVertex());
                    polygonVertices.Add(PointOn(a + da, TF(p[(i + 1) % p.Count])).ToVertex());
                    polygonVertices.Add(PointOn(a + da, TF(p[i])).ToVertex());
                    polygonVertices.Add(PointOn(a, TF(p[i])).ToVertex());
                    a += da;
                    if (!inversed)
                    {
                        polygonVertices.Reverse();
                    }
                    IdPath curPath = null;
                    if (!paths.ContainsKey(pid[i]))
                    {
                        curPath = feature.With(pid[i]);
                        paths.Add(pid[i], curPath);
                    }
                    else
                    {
                        curPath = paths[pid[i]];
                    }

                    if (isHelix)
                    {
                        var verts = new List <Vertex>();
                        verts.Add(polygonVertices[0]);
                        verts.Add(polygonVertices[1]);
                        verts.Add(polygonVertices[2]);
                        polys.Add(new Polygon(verts, curPath));

                        verts = new List <Vertex>();
                        verts.Add(polygonVertices[0]);
                        verts.Add(polygonVertices[2]);
                        verts.Add(polygonVertices[3]);
                        polys.Add(new Polygon(verts, curPath));
                    }
                    else
                    {
                        polys.Add(new Polygon(polygonVertices, curPath));
                    }
                }
            }
        }
        return(Solid.FromPolygons(polys));
    }
コード例 #24
0
 public static void GizmosDrawCube(Vector3 center, Vector3 size, Matrix4x4 matrix)
 {
     /*
      *      4-----5
      *     /|    /|
      * y  7-----6 |
      * |  | 0---|-1
      * |  |/    |/
      * |  3-----2
      * | z
      * |/_______x
      */
     Bounds bounds = new Bounds(center, size);
     Vector3 p3 = bounds.min;
     Vector3 p5 = bounds.max;
     Vector3 p0 = matrix.MultiplyPoint(new Vector3(p3.x, p3.y, p5.z));
     Vector3 p1 = matrix.MultiplyPoint(new Vector3(p5.x, p3.y, p5.z));
     Vector3 p2 = matrix.MultiplyPoint(new Vector3(p5.x, p3.y, p3.z));
     Vector3 p4 = matrix.MultiplyPoint(new Vector3(p3.x, p5.y, p5.z));
     Vector3 p6 = matrix.MultiplyPoint(new Vector3(p5.x, p5.y, p3.z));
     Vector3 p7 = matrix.MultiplyPoint(new Vector3(p3.x, p5.y, p3.z));
     p3 = matrix.MultiplyPoint(p3);
     p5 = matrix.MultiplyPoint(p5);
     Gizmos.DrawLine(p0, p1);
     Gizmos.DrawLine(p1, p2);
     Gizmos.DrawLine(p2, p3);
     Gizmos.DrawLine(p3, p0);
     Gizmos.DrawLine(p4, p5);
     Gizmos.DrawLine(p5, p6);
     Gizmos.DrawLine(p6, p7);
     Gizmos.DrawLine(p7, p4);
     Gizmos.DrawLine(p0, p4);
     Gizmos.DrawLine(p1, p5);
     Gizmos.DrawLine(p2, p6);
     Gizmos.DrawLine(p3, p7);
 }
コード例 #25
0
    public void LoadMap()
    {
        Debug.Log("Load Map is called");
        if (m_Visualizers.Count == 0)
        {
            instruction.gameObject.SetActive(true);
            return;
        }
        try
        {
            var fs = new FileStream(path + "/Map.txt", FileMode.Open, FileAccess.Read);
            using (var bs = new BufferedStream(fs))
                using (var sr = new StreamReader(bs))
                {
                    int numOfScanner = int.Parse(sr.ReadLine());
                    Debug.Log("Number of scanners are" + numOfScanner);


                    ReadFrameLowerLeft.x = float.Parse(sr.ReadLine());
                    ReadFrameLowerLeft.y = float.Parse(sr.ReadLine());
                    ReadFrameLowerLeft.z = float.Parse(sr.ReadLine());

                    ReadFrameLowerRight.x = float.Parse(sr.ReadLine());
                    ReadFrameLowerRight.y = float.Parse(sr.ReadLine());
                    ReadFrameLowerRight.z = float.Parse(sr.ReadLine());


                    ReadFrameUpperLeft.x = float.Parse(sr.ReadLine());
                    ReadFrameUpperLeft.y = float.Parse(sr.ReadLine());
                    ReadFrameUpperLeft.z = float.Parse(sr.ReadLine());


                    ReadFrameUpperRight.x = float.Parse(sr.ReadLine());
                    ReadFrameUpperRight.y = float.Parse(sr.ReadLine());
                    ReadFrameUpperRight.z = float.Parse(sr.ReadLine());

                    Debug.Log("Read lower left is" + ReadFrameLowerLeft);
                    Debug.Log("Read lower right is" + ReadFrameLowerRight);
                    Debug.Log("Read upper left is" + ReadFrameUpperLeft);
                    Debug.Log("Read upper right is" + ReadFrameUpperRight);

                    for (int i = 0; i < numOfScanner; i++)
                    {
                        var x = float.Parse(sr.ReadLine());
                        var y = float.Parse(sr.ReadLine());
                        var z = float.Parse(sr.ReadLine());
                        ScannerPos.Add(new UnityEngine.Vector3(x, y, z));
                    }
                }
            instruction.gameObject.SetActive(false);
        }
        catch (FileNotFoundException ex)
        {
            Debug.LogError("File not found");
        }
        ApplyTransformation(out TransformationMatrix);
        Pose pose;
        int  count = 1;

        foreach (var scanner in ScannerPos)
        {
            pose.position = TransformationMatrix.MultiplyPoint(scanner);
            pose.rotation = Quaternion.identity;
            var obj = Instantiate(Scanner, pose.position, pose.rotation);
            obj.transform.Rotate(-90, 0, 90);
            obj.transform.GetChild(0).GetComponent <TextMesh>().text = count.ToString();
            count++;
            Anchor anchor = Session.CreateAnchor(pose);
            obj.transform.parent = anchor.transform;
        }
    }
コード例 #26
0
 private static UnityEngine.Rect Mul(UnityEngine.Rect rect, UnityEngine.Matrix4x4 matrix)
 {
     UnityEngine.Vector3 pos  = matrix.MultiplyPoint(new UnityEngine.Vector3(rect.x, rect.y));
     UnityEngine.Vector3 size = matrix.MultiplyVector(new UnityEngine.Vector3(rect.width, rect.height));
     return(new UnityEngine.Rect(pos.x, pos.y, size.x, size.y));
 }
コード例 #27
0
		private void AdjustEdgeHandleColor(Vector3 handlePos, Vector3 slideDir1, Vector3 slideDir2, Matrix4x4 transform, float alphaFactor)
		{
			Vector3 inPoint = transform.MultiplyPoint(handlePos);
			Vector3 normalized = transform.MultiplyVector(slideDir1).normalized;
			Vector3 normalized2 = transform.MultiplyVector(slideDir2).normalized;
			bool flag;
			if (Camera.current.orthographic)
			{
				flag = (Vector3.Dot(-Camera.current.transform.forward, normalized) < 0f && Vector3.Dot(-Camera.current.transform.forward, normalized2) < 0f);
			}
			else
			{
				Plane plane = new Plane(normalized, inPoint);
				Plane plane2 = new Plane(normalized2, inPoint);
				flag = (!plane.GetSide(Camera.current.transform.position) && !plane2.GetSide(Camera.current.transform.position));
			}
			if (flag)
			{
				alphaFactor *= this.backfaceAlphaMultiplier;
			}
			if (alphaFactor < 1f)
			{
				Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, Handles.color.a * alphaFactor);
			}
		}
コード例 #28
0
ファイル: Util.cs プロジェクト: newton64/Dodecahedroads
 public static Vector3 TransformVector(Matrix4x4 m, Vector3 v)
 {
     return m.MultiplyPoint(v) - m.MultiplyPoint(Vector3.zero);
 }
コード例 #29
0
    private static void DrawFaceEditor(ref int face, OCAtlas atlas, ref UnityEngine.Matrix4x4 matrix)
    {
        UnityEngine.GUILayout.BeginVertical(UnityEngine.GUI.skin.box);
        UnityEngine.Texture texture = atlas.Texture;
        UnityEngine.Rect    rect    = UnityEngine.GUILayoutUtility.GetAspectRect((float)texture.width / texture.height);
        UnityEngine.GUILayout.EndVertical();

        UnityEngine.Matrix4x4 rectMatrix    = UnityEngine.Matrix4x4.Scale(new UnityEngine.Vector3(rect.width, rect.height, 0)) * matrix;
        UnityEngine.Matrix4x4 invRectMatrix = matrix.inverse * UnityEngine.Matrix4x4.Scale(new UnityEngine.Vector3(1 / rect.width, 1 / rect.height, 0));
        UnityEngine.Matrix4x4 invertY       = UnityEngine.Matrix4x4.TRS(new UnityEngine.Vector2(0, 1), UnityEngine.Quaternion.identity, new UnityEngine.Vector2(1, -1));

        bool mouseInRect = rect.Contains(UnityEngine.Event.current.mousePosition);

        UnityEngine.GUI.BeginGroup(rect);
        {
            UnityEngine.Vector2 mouse = invRectMatrix.MultiplyPoint(UnityEngine.Event.current.mousePosition);             // local mouse [0..1]

            if (UnityEngine.Event.current.type == UnityEngine.EventType.Repaint)
            {
                UnityEngine.Rect texturePosition = Mul(new UnityEngine.Rect(0, 0, 1, 1), rectMatrix);
                UnityEngine.Rect faceRet         = atlas.ToRect(face);
                faceRet = Mul(faceRet, rectMatrix * invertY);
                UnityEngine.GUI.DrawTexture(texturePosition, texture);
                BlockEditorUtils.DrawRect(faceRet, UnityEngine.Color.green);
            }

            if (UnityEngine.Event.current.type == UnityEngine.EventType.MouseDown && UnityEngine.Event.current.button == 0 && mouseInRect)
            {
                UnityEngine.Vector2 invMouse = invertY.MultiplyPoint(mouse);
                if (invMouse.x >= 0 && invMouse.x <= 1 && invMouse.y >= 0 && invMouse.y <= 1)
                {
                    int posX = UnityEngine.Mathf.FloorToInt(invMouse.x * atlas.Width);
                    int posY = UnityEngine.Mathf.FloorToInt(invMouse.y * atlas.Height);
                    face = posY * atlas.Width + posX;

                    UnityEngine.GUI.changed = true;
                    UnityEngine.Event.current.Use();
                }
            }

            if (UnityEngine.Event.current.type == UnityEngine.EventType.MouseDrag && UnityEngine.Event.current.button == 1 && mouseInRect)
            {
                UnityEngine.Vector3 delta = UnityEngine.Event.current.delta;
                delta.x /= rect.width;
                delta.y /= rect.height;

                UnityEngine.Matrix4x4 offsetMatrix = UnityEngine.Matrix4x4.TRS(delta, UnityEngine.Quaternion.identity, UnityEngine.Vector3.one);
                matrix = offsetMatrix * matrix;

                UnityEngine.GUI.changed = true;
                UnityEngine.Event.current.Use();
            }

            if (UnityEngine.Event.current.type == UnityEngine.EventType.ScrollWheel && mouseInRect)
            {
                float s = 0.95f;
                if (UnityEngine.Event.current.delta.y < 0)
                {
                    s = 1.0f / s;
                }

                UnityEngine.Matrix4x4 offsetMatrix = UnityEngine.Matrix4x4.TRS(mouse, UnityEngine.Quaternion.identity, UnityEngine.Vector3.one);
                matrix *= offsetMatrix;

                UnityEngine.Matrix4x4 scaleMatrix = UnityEngine.Matrix4x4.Scale(UnityEngine.Vector3.one * s);
                matrix *= scaleMatrix;

                offsetMatrix = UnityEngine.Matrix4x4.TRS(-mouse, UnityEngine.Quaternion.identity, UnityEngine.Vector3.one);
                matrix      *= offsetMatrix;

                UnityEngine.GUI.changed = true;
                UnityEngine.Event.current.Use();
            }
        }
        UnityEngine.GUI.EndGroup();
    }
コード例 #30
0
    void OnSceneGUI()
    {
        //Get tilemap
        if (tileMap == null)
        {
            tileMap = (TileMap)target;
        }

        //Toggle editing
        if (e.type == EventType.KeyDown && e.keyCode == KeyCode.Tab)
        {
            editing = !editing;
            EditorUtility.SetDirty(target);
        }

        if (editing)
        {
            //Hide mesh
            HideWireframe(true);

            //Quit on tool change
            if (e.type == EventType.KeyDown)
            {
                switch (e.keyCode)
                {
                    case KeyCode.Q:
                    case KeyCode.W:
                    case KeyCode.E:
                    case KeyCode.R:
                        return;
                }
            }

            //Quit if panning or no camera exists
            if (Tools.current == Tool.View || (e.isMouse && e.button > 1) || Camera.current == null || e.type == EventType.ScrollWheel)
            {
                return;
            }

            //Quit if laying out
            if (e.type == EventType.Layout)
            {
                HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));
                return;
            }

            //Update matrices
            Handles.matrix = tileMap.transform.localToWorldMatrix;
            worldToLocal = tileMap.transform.worldToLocalMatrix;

            //Draw axes
            Handles.color = Color.red;
            Handles.DrawLine(new Vector3(-tileMap.tileSize, tileMap.transform.position.y, 0), new Vector3(tileMap.tileSize, tileMap.transform.position.y, 0));
            Handles.DrawLine(new Vector3(0, tileMap.transform.position.y, -tileMap.tileSize), new Vector3(0, tileMap.transform.position.y, tileMap.tileSize));

            //Update mouse position
            Plane plane = new Plane(tileMap.transform.up, tileMap.transform.position);
            Ray ray = Camera.current.ScreenPointToRay(new Vector3(e.mousePosition.x, Camera.current.pixelHeight - e.mousePosition.y));
            float hit;
            if (!plane.Raycast(ray, out hit))
            {
                return;
            }

            Vector3 mousePosition = worldToLocal.MultiplyPoint(ray.GetPoint(hit));
            cursorX = Mathf.RoundToInt(mousePosition.x / tileMap.tileSize);
            cursorZ = Mathf.RoundToInt(mousePosition.z / tileMap.tileSize);

            //Update the state and repaint
            state = UpdateState();
            HandleUtility.Repaint();
            e.Use();
        }
        else
        {
            HideWireframe(false);
        }
    }
コード例 #31
0
	void TransformPoly(Matrix4x4 matrix)
	{
		for (int i = 0; i < keyPoints.Count; i++)
		{
			keyPoints[i] = matrix.MultiplyPoint(polyMesh.keyPoints[i]);
			curvePoints[i] = matrix.MultiplyPoint(polyMesh.curvePoints[i]);
		}
	}
コード例 #32
0
	void OnSceneGUI()
	{
		if (target == null)
			return;

		if (KeyPressed(editKey))
			editing = !editing;

		if (editing)
		{
			//Update lists
			if (keyPoints == null)
			{
				keyPoints = new List<Vector3>(polyMesh.keyPoints);
				curvePoints = new List<Vector3>(polyMesh.curvePoints);
				isCurve = new List<bool>(polyMesh.isCurve);
			}

			//Crazy hack to register undo
			if (undoCallback == null)
			{
				undoCallback = typeof(EditorApplication).GetField("undoRedoPerformed", BindingFlags.NonPublic | BindingFlags.Static);
				if (undoCallback != null)
					undoCallback.SetValue(null, new EditorApplication.CallbackFunction(OnUndoRedo));
			}

			//Load handle matrix
			Handles.matrix = polyMesh.transform.localToWorldMatrix;

			//Draw points and lines
			DrawAxis();
			Handles.color = Color.white;
			for (int i = 0; i < keyPoints.Count; i++)
			{
				Handles.color = nearestLine == i ? Color.green : Color.white;
				DrawSegment(i);
				if (selectedIndices.Contains(i))
				{
					Handles.color = Color.green;
					DrawCircle(keyPoints[i], 0.08f);
				}
				else
					Handles.color = Color.white;
				DrawKeyPoint(i);
				if (isCurve[i])
				{
					Handles.color = (draggingCurve && dragIndex == i) ? Color.white : Color.blue;
					DrawCurvePoint(i);
				}
			}

			//Quit on tool change
			if (e.type == EventType.KeyDown)
			{
				switch (e.keyCode)
				{
				case KeyCode.Q:
				case KeyCode.W:
				case KeyCode.E:
				case KeyCode.R:
					return;
				}
			}

			//Quit if panning or no camera exists
			if (Tools.current == Tool.View || (e.isMouse && e.button > 0) || Camera.current == null || e.type == EventType.ScrollWheel)
				return;

			//Quit if laying out
			if (e.type == EventType.Layout)
			{
				HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));
				return;
			}

			//Cursor rectangle
			EditorGUIUtility.AddCursorRect(new Rect(0, 0, Camera.current.pixelWidth, Camera.current.pixelHeight), mouseCursor);
			mouseCursor = MouseCursor.Arrow;

			//Extrude key state
			if (e.keyCode == extrudeKey)
			{
				if (extrudeKeyDown)
				{
					if (e.type == EventType.KeyUp)
						extrudeKeyDown = false;
				}
				else if (e.type == EventType.KeyDown)
					extrudeKeyDown = true;
			}

			//Update matrices and snap
			worldToLocal = polyMesh.transform.worldToLocalMatrix;
			inverseRotation = Quaternion.Inverse(polyMesh.transform.rotation) * Camera.current.transform.rotation;
			snap = gridSnap;
			
			//Update mouse position
			screenMousePosition = new Vector3(e.mousePosition.x, Camera.current.pixelHeight - e.mousePosition.y);
			var plane = new Plane(-polyMesh.transform.forward, polyMesh.transform.position);
			var ray = Camera.current.ScreenPointToRay(screenMousePosition);
			float hit;
			if (plane.Raycast(ray, out hit))
				mousePosition = worldToLocal.MultiplyPoint(ray.GetPoint(hit));
			else
				return;

			//Update nearest line and split position
			nearestLine = NearestLine(out splitPosition);
			
			//Update the state and repaint
			var newState = UpdateState();
			if (state != newState)
				SetState(newState);
			HandleUtility.Repaint();
			e.Use();
		}
	}
コード例 #33
0
    void DrawScreen(Matrix4x4 matrix, Color color)
    {
        HeadTracker headTracking = target as HeadTracker;

        float left = headTracking.m_OriginalLeft;
        float right = headTracking.m_OriginalRight;
        float top = headTracking.m_OriginalTop;
        float bottom = headTracking.m_OriginalBottom;

        Vector3 topLeft = new Vector3 (left, top);
        Vector3 topRight = new Vector3 (right, top);
        Vector3 bottomLeft = new Vector3 (left, bottom);
        Vector3 bottomRight = new Vector3 (right, bottom);

        topLeft = matrix.MultiplyPoint (topLeft);
        topRight = matrix.MultiplyPoint (topRight);
        bottomLeft = matrix.MultiplyPoint (bottomLeft);
        bottomRight = matrix.MultiplyPoint (bottomRight);

        Handles.color = color;
        Handles.DrawLine (topLeft, topRight);
        Handles.DrawLine (topRight, bottomRight);
        Handles.DrawLine (bottomRight, bottomLeft);
        Handles.DrawLine (bottomLeft, topLeft);
    }
コード例 #34
0
    static bool Matrix4x4_MultiplyPoint__Vector3(JSVCall vc, int argc)
    {
        int len = argc;

        if (len == 1)
        {
            UnityEngine.Vector3   arg0    = (UnityEngine.Vector3)JSApi.getVector3S((int)JSApi.GetType.Arg);
            UnityEngine.Matrix4x4 argThis = (UnityEngine.Matrix4x4)vc.csObj;                JSApi.setVector3S((int)JSApi.SetType.Rval, argThis.MultiplyPoint(arg0));
            JSMgr.changeJSObj(vc.jsObjID, argThis);
        }

        return(true);
    }
コード例 #35
0
 private static float SizeHandle(Vector3 localPos, Vector3 localPullDir, Matrix4x4 matrix, bool isEdgeHandle)
 {
     float num3;
     Vector3 rhs = matrix.MultiplyVector(localPullDir);
     Vector3 position = matrix.MultiplyPoint(localPos);
     float handleSize = HandleUtility.GetHandleSize(position);
     bool changed = GUI.changed;
     GUI.changed = false;
     Color color = Handles.color;
     float num2 = 0f;
     if (isEdgeHandle)
     {
         num2 = Mathf.Cos(0.7853982f);
     }
     if (Camera.current.orthographic)
     {
         num3 = Vector3.Dot(-Camera.current.transform.forward, rhs);
     }
     else
     {
         Vector3 vector3 = Camera.current.transform.position - position;
         num3 = Vector3.Dot(vector3.normalized, rhs);
     }
     if (num3 < -num2)
     {
         Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, Handles.color.a * Handles.backfaceAlphaMultiplier);
     }
     if (<>f__mg$cache0 == null)
     {
コード例 #36
0
		private void AdjustMidpointHandleColor(Vector3 localPos, Vector3 localTangent, Vector3 localBinormal, Matrix4x4 transform, float alphaFactor, bool isCameraInsideBox)
		{
			if (!isCameraInsideBox)
			{
				Vector3 b = transform.MultiplyPoint(localPos);
				Vector3 lhs = transform.MultiplyVector(localTangent);
				Vector3 rhs = transform.MultiplyVector(localBinormal);
				Vector3 normalized = Vector3.Cross(lhs, rhs).normalized;
				float num;
				if (Camera.current.orthographic)
				{
					num = Vector3.Dot(-Camera.current.transform.forward, normalized);
				}
				else
				{
					num = Vector3.Dot((Camera.current.transform.position - b).normalized, normalized);
				}
				if (num < -0.0001f)
				{
					alphaFactor *= this.backfaceAlphaMultiplier;
				}
			}
			if (alphaFactor < 1f)
			{
				Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, Handles.color.a * alphaFactor);
			}
		}
コード例 #37
0
ファイル: MegaHose.cs プロジェクト: Morac/Orca6
    // we only need to build the savevertex and uvs if mesh def changes, else we can keep the uvs
    void BuildMesh()
    {
        if ( !mesh )
        {
            mesh = GetComponent<MeshFilter>().sharedMesh;
            if ( mesh == null )
            {
                updatemesh = true;
                return;
            }
        }

        if ( hosespline.knots.Count == 0 )
        {
            hosespline.AddKnot(Vector3.zero, Vector3.zero, Vector3.zero);
            hosespline.AddKnot(Vector3.zero, Vector3.zero, Vector3.zero);
        }

        FixHoseFillet();

        bool createfree = freecreate;

        if ( (!createfree) && ((!custnode) || (!custnode2)) )
            createfree = true;

        if ( custnode && custnode2 )
            createfree = false;

        Matrix4x4 mat1,mat2;
        float Lf = 0.0f;
        Tlocal = Matrix4x4.identity;

        Vector3 startvec, endvec, startpoint, endpoint, endy;
        starty = Vector3.zero;
        roty = Vector3.zero;
        yangle = 0.0f;

        Vector3 RV = Vector3.zero;

        if ( createfree )
            Lf = noreflength;
        else
        {
            RV = up;	//new Vector3(xtmp, ytmp, ztmp);

            mat1 = custnode.transform.localToWorldMatrix;
            mat2 = custnode2.transform.localToWorldMatrix;

            Matrix4x4 mato1 = Matrix4x4.identity;
            Matrix4x4 mato2 = Matrix4x4.identity;
            mato1 = Matrix4x4.TRS(offset, Quaternion.Euler(rotate), scale);
            mato1 = mato1.inverse;

            mato2 = Matrix4x4.TRS(offset1, Quaternion.Euler(rotate1), scale1);
            mato2 = mato2.inverse;
            S = transform.localToWorldMatrix;

            Matrix4x4 mat1NT, mat2NT;

            mat1NT = mat1;
            mat2NT = mat2;
            MegaMatrix.NoTrans(ref mat1NT);
            MegaMatrix.NoTrans(ref mat2NT);
            Vector3 P1 = mat1.MultiplyPoint(mato1.GetColumn(3));
            Vector3 P2 = mat2.MultiplyPoint(mato2.GetColumn(3));

            startvec = mat1NT.MultiplyPoint(mato1.GetColumn(2));
            endvec = mat2NT.MultiplyPoint(mato2.GetColumn(2));
            starty = mat1NT.MultiplyPoint(mato1.GetColumn(1));
            endy = mat2NT.MultiplyPoint(mato2.GetColumn(1));

            Matrix4x4 SI = S.inverse;

            Vector3 P0 = SI.MultiplyPoint(P1);
            Matrix4x4 T1 = mat1;
            MegaMatrix.NoTrans(ref T1);

            Vector3 RVw = T1.MultiplyPoint(RV);
            Lf = (P2 - P1).magnitude;
            Vector3 Zw;
            if ( Lf < 0.01f )
                Zw = P1.normalized;
            else
                Zw = (P2 - P1).normalized;
            Vector3 Xw = Vector3.Cross(RVw, Zw).normalized;
            Vector3 Yw = Vector3.Cross(Zw, Xw).normalized;

            MegaMatrix.NoTrans(ref SI);

            Vector3 Xs = SI.MultiplyPoint(Xw);
            Vector3 Ys = SI.MultiplyPoint(Yw);
            Vector3 Zs = SI.MultiplyPoint(Zw);
            Tlocal.SetColumn(0, Xs);
            Tlocal.SetColumn(1, Ys);
            Tlocal.SetColumn(2, Zs);
            MegaMatrix.SetTrans(ref Tlocal, P0);

            // move z-axes of end transforms into local frame
            Matrix4x4 TlocalInvNT = Tlocal;
            MegaMatrix.NoTrans(ref TlocalInvNT);

            TlocalInvNT = TlocalInvNT.inverse;

            float tenstop = tension1;	// * 0.01f;
            float tensbot = tension2;	// * 0.01f;

            startvec = tensbot * (TlocalInvNT.MultiplyPoint(startvec));
            endvec = tenstop * (TlocalInvNT.MultiplyPoint(endvec));

            starty = TlocalInvNT.MultiplyPoint(starty);
            endy = TlocalInvNT.MultiplyPoint(endy);

            yangle = Mathf.Acos(Vector3.Dot(starty, endy));

            if ( yangle > EPSILON )
                roty = Vector3.Cross(starty, endy).normalized;
            else
                roty = Vector3.zero;

            startpoint = Vector3.zero;
            endpoint = new Vector3(0.0f, 0.0f, Lf);

            hosespline.knots[0].p = startpoint;
            hosespline.knots[0].invec = startpoint - startvec;
            hosespline.knots[0].outvec = startpoint + startvec;

            hosespline.knots[1].p = endpoint;
            hosespline.knots[1].invec = endpoint + endvec;
            hosespline.knots[1].outvec = endpoint - endvec;

            hosespline.CalcLength();	//10);
        }

        MegaHoseType wtype = wiretype;

        int Segs = segments;
        if ( Segs < 3 )
            Segs = 3;

        if ( rebuildcross )
        {
            rebuildcross = false;
            int	nfillets = 0;
            int nsides = 0;

            if ( wtype == MegaHoseType.Round )
            {
                NvertsPerRing = rndsides;
                if ( NvertsPerRing < 3 )
                    NvertsPerRing = 3;
            }
            else
            {
                if ( wtype == MegaHoseType.Rectangle )
                {
                    nfillets = rectfilletsides;
                    if ( nfillets < 0 )
                        nfillets = 0;

                    if ( smooth == MegaHoseSmooth.SMOOTHNONE )
                        NvertsPerRing = (nfillets > 0 ? 8 + 4 * (nfillets - 1) : 8);
                    else
                        NvertsPerRing = (nfillets > 0 ? 8 + 4 * (nfillets - 1) : 4);	//4);
                }
                else
                {
                    nfillets = dsecfilletsides;
                    if ( nfillets < 0 )
                        nfillets = 0;
                    nsides = dsecrndsides;
                    if ( nsides < 2 )
                        nsides = 2;
                    int nsm1 = nsides - 1;
                    NvertsPerRing = (nfillets > 0 ? 6 + nsm1 + 2 * (nfillets - 1): 4 + nsm1);
                }
            }

            NvertsPerRing++;

            int NfacesPerEnd,NfacesPerRing,Nfaces = 0;
            //MegaHoseSmooth SMOOTH = smooth;

            Nverts = (Segs + 1) * (NvertsPerRing + 1);	// + 2;
            if ( capends )
                Nverts += 2;

            NfacesPerEnd = NvertsPerRing;
            NfacesPerRing = 6 * NvertsPerRing;
            Nfaces =  Segs * NfacesPerRing;	// + 2 * NfacesPerEnd;

            if ( capends )
            {
                Nfaces += 2 * NfacesPerEnd;
            }

            if ( SaveVertex == null || SaveVertex.Length != NvertsPerRing )
            {
                SaveVertex = new Vector3[NvertsPerRing];
                SaveUV = new Vector2[NvertsPerRing];
            }

            if ( calcnormals )
            {
                if ( SaveNormals == null || SaveNormals.Length != NvertsPerRing )
                    SaveNormals = new Vector3[NvertsPerRing];
            }

            MakeSaveVertex(NvertsPerRing, nfillets, nsides, wtype);

            if ( verts == null || verts.Length != Nverts )
            {
                verts = new Vector3[Nverts];
                uvs = new Vector2[Nverts];
                faces = new int[Nfaces * 3];
            }

            if ( calcnormals && (normals == null || normals.Length != Nverts) )
                normals = new Vector3[Nverts];
        }

        if ( Nverts == 0 )
            return;

        bool mapmenow = mapmemapme;

        int thisvert = 0;
        int	last = Nverts - 1;
        int last2 = last - 1;
        int lastvpr = NvertsPerRing;	// - 1;
        int maxseg = Segs + 1;

        float flexhere;
        float dadjust;
        float flexlen;
        float flex1 = flexstart;
        float flex2 = flexstop;
        int flexn = flexcycles;
        float flexd = flexdiameter;

        Vector3 ThisPosition;
        Vector3 ThisXAxis, ThisYAxis, ThisZAxis;
        Vector2 uv = Vector2.zero;

        Matrix4x4 RingTM = Matrix4x4.identity;
        Matrix4x4 invRingTM = Matrix4x4.identity;

        for ( int i = 0; i < maxseg; i++ )
        {
            float incr = (float)i / (float)Segs;

            if ( createfree )
            {
                ThisPosition = new Vector3(0.0f, 0.0f, Lf * incr);
                ThisXAxis = new Vector3(1.0f, 0.0f, 0.0f);
                ThisYAxis = new Vector3(0.0f, 1.0f, 0.0f);
                ThisZAxis = new Vector3(0.0f, 0.0f, 1.0f);
            }
            else
            {
                int k = 0;
                ThisPosition = hosespline.InterpCurve3D(incr, true, ref k);
                ThisZAxis = (hosespline.InterpCurve3D(incr + 0.001f, true, ref k) - ThisPosition).normalized;

                ThisYAxis = starty;
                if ( yangle > EPSILON )
                    RotateOnePoint(ref ThisYAxis, Vector3.zero, roty, incr * yangle);

                ThisXAxis = Vector3.Cross(ThisYAxis, ThisZAxis).normalized;

                ThisYAxis = Vector3.Cross(ThisZAxis, ThisXAxis);
            }

            RingTM.SetColumn(0, ThisXAxis);
            RingTM.SetColumn(1, ThisYAxis);
            RingTM.SetColumn(2, ThisZAxis);
            MegaMatrix.SetTrans(ref RingTM, ThisPosition);

            if ( !createfree )
            {
                RingTM = Tlocal * RingTM;
            }

            if ( calcnormals )
            {
                invRingTM = RingTM;
                MegaMatrix.NoTrans(ref invRingTM);
                //invRingTM = invRingTM.inverse.transpose;
            }

            if ( (incr > flex1) && (incr < flex2) && flexon )
            {
                flexlen = flex2 - flex1;
                if ( flexlen < 0.01f )
                    flexlen = 0.01f;
                flexhere = (incr - flex1) / flexlen;

                float ang = (float)flexn * flexhere * (Mathf.PI * 2.0f) + PIover2;
                dadjust = 1.0f + flexd * (1.0f - Mathf.Sin(ang));	//(float)flexn * flexhere * (Mathf.PI * 2.0f) + PIover2));
            }
            else
                dadjust = 0.0f;

            if ( usebulgecurve )
            {
                if ( dadjust == 0.0f )
                    dadjust = 1.0f + (bulge.Evaluate(incr + bulgeoffset) * bulgeamount);
                else
                    dadjust += bulge.Evaluate(incr + bulgeoffset) * bulgeamount;
            }

            uv.x = 0.999999f * incr * uvscale.x;

            for ( int j = 0; j < NvertsPerRing; j++ )
            {
                int jj = j;	// % NvertsPerRing;

                if ( mapmenow )
                {
                    uv.y = SaveUV[jj].y;
                    uvs[thisvert] = uv;	//new Vector2(0.999999f * incr * uvscale.x, SaveUV[jj].y);
                }

                if ( dadjust != 0.0f )
                {
                    verts[thisvert] = RingTM.MultiplyPoint(dadjust * SaveVertex[jj]);
                }
                else
                {
                    verts[thisvert] = RingTM.MultiplyPoint(SaveVertex[jj]);
                }

                if ( calcnormals )
                    normals[thisvert] = invRingTM.MultiplyPoint(SaveNormals[jj]).normalized;	//.MultiplyPoint(-SaveNormals[jj]);
                //if ( j == 0 )
                //{
                //	Debug.Log("norm " + normals[thisvert].ToString("0.000") + " save " + SaveNormals[jj].ToString("0.000"));
                //}

                thisvert++;
            }

            if ( mapmenow )
            {
                //uvs[Nverts + i] = new Vector2(0.999999f * incr, 0.999f);
            }

            if ( capends )
            {
                if ( i == 0 )
                {
                    verts[last2] = (createfree ? ThisPosition : Tlocal.MultiplyPoint(ThisPosition));
                    if ( mapmenow )
                        uvs[last2] = Vector3.zero;
                }
                else
                {
                    if ( i == Segs )
                    {
                        verts[last] = createfree ? ThisPosition : Tlocal.MultiplyPoint(ThisPosition);
                        if ( mapmenow )
                        {
                            uvs[last] = Vector3.zero;
                        }
                    }
                }
            }
        }

        //	Now, set up the faces
        int thisface = 0, v1, v2, v3, v4;
        v3 = last2;
        if ( capends )
        {
            for ( int i = 0; i < NvertsPerRing - 1; i++ )
            {
                v1 = i;
                v2 = (i < lastvpr ? v1 + 1 : v1 - lastvpr);
                //v5 = (i < lastvpr ? v2 : Nverts);

                faces[thisface++] = v2;
                faces[thisface++] = v1;
                faces[thisface++] = v3;
            }
        }

        int ringnum = NvertsPerRing;	// + 1;

        for ( int i = 0; i < Segs; i++ )
        {
            for ( int j = 0; j < NvertsPerRing - 1; j++ )
            {
                v1 = i * ringnum + j;
                v2 = v1 + 1;	//(j < lastvpr? v1 + 1 : v1 - lastvpr);
                v4 = v1 + ringnum;
                v3 = v2 + ringnum;
                faces[thisface++] = v1;
                faces[thisface++] = v2;
                faces[thisface++] = v3;
                faces[thisface++] = v1;
                faces[thisface++] = v3;
                faces[thisface++] = v4;
            }
        }

        int basevert = Segs * ringnum;	//NvertsPerRing;

        v3 = Nverts - 1;
        if ( capends )
        {
            for ( int i = 0; i < NvertsPerRing - 1; i++ )
            {
                v1 = i + basevert;
                v2 = (i < lastvpr? v1 + 1 : v1 - lastvpr);
                //v5 = (i < lastvpr? v2 : Nverts + Segs);
                faces[thisface++] = v1;
                faces[thisface++] = v2;
                faces[thisface++] = v3;
            }
        }

        mesh.Clear();

        mesh.subMeshCount = 1;

        mesh.vertices = verts;
        mesh.uv = uvs;
        mesh.triangles = faces;

        if ( calcnormals )
            mesh.normals = normals;
        else
            mesh.RecalculateNormals();
        mesh.RecalculateBounds();

        if ( optimize )
        {
            mesh.Optimize();
        }

        if ( calctangents )
        {
            MegaUtils.BuildTangents(mesh);
        }

        if ( recalcCollider )
        {
            if ( meshCol == null )
                meshCol = GetComponent<MeshCollider>();

            if ( meshCol != null )
            {
                meshCol.sharedMesh = null;
                meshCol.sharedMesh = mesh;
                //bool con = meshCol.convex;
                //meshCol.convex = con;
            }
        }
    }
コード例 #38
0
    internal void ApplyTransform( Matrix4x4 transform )
    {
        var count = Vertices.Count;

        var rawVerts = Vertices.Items;
        for( int i = 0; i < count; i++ )
        {
            rawVerts[ i ] = transform.MultiplyPoint( rawVerts[ i ] );
        }

        if( Normals.Count > 0 )
        {
            var rawNormals = Normals.Items;
            for( int i = 0; i < count; i++ )
            {
                rawNormals[ i ] = transform.MultiplyVector( rawNormals[ i ] );
            }
        }
    }
コード例 #39
0
ファイル: MeshUtils.cs プロジェクト: ttldtor/NoteCAD
    public static Solid CreateSolidExtrusion(List <List <Entity> > entitiyLoops, float extrude, UnityEngine.Matrix4x4 tf, IdPath feature)
    {
        var  ids      = new List <List <Id> >();
        var  polygons = Sketch.GetPolygons(entitiyLoops, ref ids);
        bool inversed = extrude < 0f;

        var polys = new List <Polygon>();

        Func <Vector3, Vector3> TF = v => tf.MultiplyPoint(v);

        for (int pi = 0; pi < polygons.Count; pi++)
        {
            var p         = polygons[pi];
            var pid       = ids[pi];
            var pv        = new List <Vector3>(p);
            var triangles = Triangulation.Triangulate(pv);

            IdPath polyId        = feature.With(new Id(-1));
            bool   invComp       = true;
            var    shift         = Vector3.zero;
            var    extrudeVector = Vector3.forward * extrude;

            for (int side = 0; side < 2; side++)
            {
                for (int i = 0; i < triangles.Count / 3; i++)
                {
                    var polygonVertices = new List <Vertex>();
                    for (int j = 0; j < 3; j++)
                    {
                        polygonVertices.Add(TF(triangles[i * 3 + j] + shift).ToVertex());
                    }
                    if (inversed == invComp)
                    {
                        polygonVertices.Reverse();
                    }
                    polys.Add(new Polygon(polygonVertices, polyId));
                }
                polyId  = feature.With(new Id(-2));
                invComp = false;
                shift   = extrudeVector;
            }

            Dictionary <Id, IdPath> paths = new Dictionary <Id, IdPath>();
            for (int i = 0; i < p.Count; i++)
            {
                var polygonVertices = new List <Vertex>();
                polygonVertices.Add(TF(p[i]).ToVertex());
                polygonVertices.Add(TF(p[(i + 1) % p.Count]).ToVertex());
                polygonVertices.Add(TF((p[(i + 1) % p.Count] + extrudeVector)).ToVertex());
                polygonVertices.Add(TF((p[i] + extrudeVector)).ToVertex());
                if (!inversed)
                {
                    polygonVertices.Reverse();
                }
                IdPath curPath = null;
                if (!paths.ContainsKey(pid[i]))
                {
                    curPath = feature.With(pid[i]);
                    paths.Add(pid[i], curPath);
                }
                else
                {
                    curPath = paths[pid[i]];
                }
                polys.Add(new Polygon(polygonVertices, curPath));
            }
        }
        return(Solid.FromPolygons(polys));
    }
コード例 #40
0
    public void UpdateTrail(float currentTime, float deltaTime)
    {
        // ** call once a frame **

        // Rebuild the mesh
        mesh.Clear();
        //
        // Remove old sections
        while (sections.Count > 0 && currentTime > sections[sections.Count - 1].time + time) {
            sections.RemoveAt(sections.Count - 1);
        }
        // We need at least 2 sections to create the line
        if (sections.Count < 2)
            return;
        //
        vertices = new Vector3[sections.Count * 2];
        colors = new Color[sections.Count * 2];
        uv = new Vector2[sections.Count * 2];
        //
        currentSection = sections[0];
        //
        // Use matrix instead of transform.TransformPoint for performance reasons
        localSpaceTransform = transform.worldToLocalMatrix;

        // Generate vertex, uv and colors
        for (var i = 0; i < sections.Count; i++) {
            //
            currentSection = sections[i];
            // Calculate u for texture uv and color interpolation
            float u = 0.0f;
            if (i != 0)
                u = Mathf.Clamp01((currentTime - currentSection.time) / time);
            //
            // Calculate upwards direction
            Vector3 upDir = currentSection.upDir;

            // Generate vertices
            vertices[i * 2 + 0] = localSpaceTransform.MultiplyPoint(currentSection.point);
            vertices[i * 2 + 1] = localSpaceTransform.MultiplyPoint(currentSection.point + upDir * height);

            uv[i * 2 + 0] = new Vector2(u, 0);
            uv[i * 2 + 1] = new Vector2(u, 1);

            // fade colors out over time
            Color interpolatedColor = Color.Lerp(startColor, endColor, u);
            colors[i * 2 + 0] = interpolatedColor;
            colors[i * 2 + 1] = interpolatedColor;
        }

        // Generate triangles indices
        int[] triangles = new int[(sections.Count - 1) * 2 * 3];
        for (int i = 0; i < triangles.Length / 6; i++) {
            triangles[i * 6 + 0] = i * 2;
            triangles[i * 6 + 1] = i * 2 + 1;
            triangles[i * 6 + 2] = i * 2 + 2;

            triangles[i * 6 + 3] = i * 2 + 2;
            triangles[i * 6 + 4] = i * 2 + 1;
            triangles[i * 6 + 5] = i * 2 + 3;
        }

        // Assign to mesh
        mesh.vertices = vertices;
        mesh.colors = colors;
        mesh.uv = uv;
        mesh.triangles = triangles;
        //
        // Tween to the desired time
        //
        if (time > desiredTime){
            time -= deltaTime*timeTransitionSpeed;
            if(time <= desiredTime) time = desiredTime;
        } else if (time < desiredTime){
            time += deltaTime*timeTransitionSpeed;
            if(time >= desiredTime) time = desiredTime;
        }
    }
コード例 #41
0
ファイル: Anim.cs プロジェクト: Cabriter/DotaLegend
    void Update()
    {
        currentTime += Time.deltaTime;

        int frm = (int)(currentTime / frameSpeed);//当前播放的帧数

        if (currentAnimation == null) return;//没动画就跳出

        if (currentAnimation.frames.Count <= frm) //当前帧是最后一帧的话善后
        {
            if (playOnce) return;//如果是重复播放就重置值
            frm = 0;
            currentTime = 0;
        }

        foreach (KeyValuePair<string, GameObject> g in spriteDic) //全部骨骼隐藏
        {
            g.Value.SetActive(false);
        }

        frame currentFrame = currentAnimation.frames[frm];//当前帧的信息

        List<boneData> boneList = currentFrame.boneList;//当前帧所有骨骼的信息

        for (int i = 0; i < boneList.Count; i++)
        {
            float a = boneList[i].data[0];
            float b = boneList[i].data[1];
            float c = boneList[i].data[2];
            float d = boneList[i].data[3];
            float tx = boneList[i].data[4];
            float ty = boneList[i].data[5];
            //float a, b, c, d, tx, ty;   //test

            int index = boneList[i].boneIndex;

            string spriteName = string.Empty;

            for (int j = 0; j < animation.boneList.Count; j++)
            {
                if (animation.boneList[j].index == index)
                {
                    spriteName = animation.boneList[j].textureName;
                    spriteDic[spriteName].SetActive(true);
                    break;
                }
            }

            //构建矩阵,萃取位置,旋转和缩放信息
            Matrix4x4 matrix = new Matrix4x4();

            matrix.m00 = a; matrix.m01 = c; matrix.m02 = 0; matrix.m03 = tx;
            matrix.m10 = b; matrix.m11 = d; matrix.m12 = 0; matrix.m13 = ty;
            matrix.m20 = 0; matrix.m21 = 0; matrix.m22 = 1; matrix.m23 = 0;
            matrix.m30 = 0; matrix.m31 = 0; matrix.m32 = 0; matrix.m33 = 1;

            //calc position
            Vector3 pos = matrix.MultiplyPoint(Vector3.zero);

            //calc rotation
            Vector3 rotation = matrix.MultiplyPoint(new Vector3(0, 1, 0));
            rotation.x -= pos.x;
            rotation.y -= pos.y;

            float degree = GetAngle(rotation, new Vector2(0, 1));
            float angle = degree * 180f / Mathf.PI;

            //calc scale
            float sx = Mathf.Sign(a) * Mathf.Sqrt(Mathf.Pow(a, 2) + Mathf.Pow(b, 2));
            float sy = Mathf.Sign(d) * Mathf.Sqrt(Mathf.Pow(c, 2) + Mathf.Pow(d, 2));

            //赋值
            spriteDic[spriteName].transform.localPosition = new Vector3(pos.x / 100, pos.y / 100);
            spriteDic[spriteName].transform.localScale = new Vector3(sx,sy, 1);
            SpriteInfo si = spriteDic[spriteName].GetComponent<SpriteInfo>();
            float temp = si.needRotated ? 90f : 0;
            spriteDic[spriteName].transform.localEulerAngles = new Vector3(0, 0, 360 - angle + temp);

            SpriteRenderer sr = spriteDic[spriteName].GetComponent<SpriteRenderer>();
            sr.sortingLayerName = i.ToString();//控制渲染层级
        }
    }