Esempio n. 1
0
        public BrickShader(GraphicsInterface gi)
            : base(gi)
        {
            //Console.WriteLine("BrickShader Link Log: \n{0}", InfoLog);
            GLSLVertexShader vShader = new GLSLVertexShader(gi, Brick_VertexSource);
            AttachShader(vShader);


            GLSLFragmentShader fShader = new GLSLFragmentShader(gi, Brick_FragmentSource);
            AttachShader(fShader);

            Link();

            // Do an initial selection so that all the variables can be located
            Bind();

            BrickColor_Pos = GetUniformLocation("BrickColor");
            MortarColor_Pos = GetUniformLocation("MortarColor");
            BrickSize_Pos = GetUniformLocation("BrickSize");
            BrickPct_Pos = GetUniformLocation("BrickPct");
            
            // From the Vertex Shader
            LightPosition_Pos = GetUniformLocation("LightPosition");

            // Set some initial values
            BrickColor = new ColorRGBA(1.0f, 0.3f, 0.2f);
            MortarColor = new ColorRGBA(0.85f, 0.86f, 0.84f);
            BrickSize = new float2(0.30f, 0.15f);
            BrickPct = new float2(0.90f, 0.85f);
            LightPosition = new Vector3f(0.0f, 0.0f, 4.0f);

            // Unselect so we start in an unselected state
            Unbind();
        }
Esempio n. 2
0
		public int Raycast(Ray ray, uint[] triangles, Vector3f[] vertices, List<int> triangleMap)
		{
			double closestDist = double.MaxValue;
			int closestHit = -1;
			for (int i = 0; i < triangles.Length; i += 3)
			{
				Vector3 p0 = (Vector3)vertices[triangles[i+0]];
				Vector3 p1 = (Vector3)vertices[triangles[i+1]];
				Vector3 p2 = (Vector3)vertices[triangles[i+2]];
				
				Plane plane = new Plane(p0, p1, p2);
				//Console.WriteLine(i+" "+plane);
				double dist;
				if (plane.Raycast(ray, out dist))
				{
					Vector3 hitPoint = ray.origin+ray.direction*dist;
					Vector3 bary = MathUtil.Barycentric(p0, p1, p2, hitPoint);

					if (MathUtil.BarycentricIsInside(bary))
					{
						if (dist < closestDist)
						{
							closestDist = dist;
							closestHit = triangleMap[i/3];
						}
					}
				}
			}

			return closestHit;
		}
Esempio n. 3
0
 public Vector4f(Vector3f source, float w)
 {
     X = source.X;
     Y = source.Y;
     Z = source.Z;
     W = w;
 }
Esempio n. 4
0
File: Mdl.cs Progetto: Frassle/Ibasa
            internal Bone(string name, int parent, ImmutableArray<int> boneControllers,
                Vector3f position, Quaternionf quaternion, Vector3f rotation, Vector3f positionScale, Vector3f rotationScale,
                Matrix4x4f poseToBone, Quaternionf alignment,
                int flags, int procType, int procIndex, int physicsBone, int surfacePropIdx, int contents)
            {
                Name = name;
                Parent = parent;
                BoneControllers = boneControllers;

                Position = position;
                Quaternion = quaternion;
                Rotation = rotation;

                PositionScale = positionScale;
                RotationScale = rotationScale;

                PoseToBone = poseToBone;
                Alignment = alignment;
                Flags = flags;
                ProcType = procType;
                ProcIndex = procIndex;
                PhysicsBone = physicsBone;
                SurfacePropIdx = surfacePropIdx;
                Contents = contents;
            }
Esempio n. 5
0
 public Cylinder3f( Vector3f origin, Vector3f axis, float radius, float height )
 {
     this.origin = origin;
     this.axis = axis;
     this.radius = radius;
     this.height = height;
 }
Esempio n. 6
0
        public static Vector4f ExtractBackgroundColor( Vector4f composite, Vector4f foreground )
        {
            // c = composite, f = foreground, b = background
            // red channel:
	        // c_r = f_a * f_r + ( 1 - f_a ) * b_r
	        // ==> b_r = ( c_r - f_a * f_r ) / ( 1 - f_a )
	        //
	        // alpha channel:
	        // c_a = f_a + b_a * ( 1 - f_a )
	        // ==> b_a = ( c_a - f_a ) / ( 1 - f_a )

            Vector3f compositeRGB = composite.XYZ;
            Vector3f foregroundRGB = foreground.XYZ;
            float ca = composite.w;
            float fa = foreground.w;

            if( fa > 0 && fa < 1 ) // partially transparent
            {
                var backgroundRGB = new Vector3f( compositeRGB - fa * foregroundRGB ) / ( 1.0f - fa );
                var ba = ( ca - fa ) / ( 1 - fa );

                return new Vector4f( backgroundRGB, ba ).Saturate();
            }
            else if( fa < 0.5f ) // foreground is fully transparent: background = input
            {
                return composite;
            }
            else // fa == 1, foreground is completely opaque, have no idea what the background is, return opaque black
            {
                // return new Vector4f( 0, 0, 0, 1 );
                return Vector4f.Zero;
            }
        }
Esempio n. 7
0
        public MDXSubmesh(byte[] data)
        {
            using (MemoryStream ms = new MemoryStream(data))
            {
                using (BinaryReader br = new BinaryReader(ms))
                {
                    this.PartID = br.ReadUInt32();
                    this.StartVertexIndex = br.ReadUInt16();
                    this.VertexCount = br.ReadUInt16();
                    this.StartTriangleIndex = br.ReadUInt16();
                    this.TriangleCount = br.ReadUInt16();
                    this.BoneCount = br.ReadUInt16();
                    this.StartBoneIndex = br.ReadUInt16();
                    this.InfluencingBonesIndex = br.ReadUInt16();
                    this.RootBoneIndex = br.ReadUInt16();
                    this.SubmeshMedianPoint = br.ReadVector3f();

                    if (br.BaseStream.Length > 32)
                    {
                        this.BoundingShellMedianPoint = br.ReadVector3f();
                        this.BoundingSphereRadius = br.ReadSingle();
                    }
                }
            }
        }
Esempio n. 8
0
File: Phy.cs Progetto: Frassle/Ibasa
        private void Load(Stream stream)
        {
            BinaryReader reader = new BinaryReader(stream, Encoding.ASCII);

            if (reader.ReadInt32() != 16)
                throw new InvalidDataException("File header is not 16.");

            Id = reader.ReadInt32();
            int solids = reader.ReadInt32();
            Checksum = reader.ReadInt32();


            for (int i = 0; i < solids; ++i)
            {
                int solidSize = reader.ReadInt32();
                string vphysics = Encoding.ASCII.GetString(reader.ReadBytes(4));
                int version = reader.ReadUInt16();
                int modelType = reader.ReadUInt16();
                int surfaceSize = reader.ReadInt32();
                Vector3f dragAxisAreas = new Vector3f(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
                int axisMapSize = reader.ReadInt32();

                if (vphysics == "VPHY")
                {

                }
            }
        }
Esempio n. 9
0
		public void OnUpdate()
		{
			if (mesh)
			{
				mesh.Dispose();
			}

			Rect rect = rectTransform.rect;
			positionVboData[0] = new Vector3f((float)rect.min.X, (float)rect.min.Y, 0);
			positionVboData[1] = new Vector3f((float)rect.min.X, (float)rect.max.Y, 0);
			positionVboData[2] = new Vector3f((float)rect.max.X, (float)rect.max.Y, 0);
			positionVboData[3] = new Vector3f((float)rect.max.X, (float)rect.min.Y, 0);
			
			mesh = new Mesh();

			mesh.AddBuffer<VertexBufferObject3f>("vertex");
			mesh.SetBuffer3f("vertex", positionVboData);

			mesh.AddBuffer<VertexBufferObject3f>("normal");
			mesh.SetBuffer3f("normal", normalVboData);

			mesh.AddBuffer<VertexBufferObject2f>("uv0");
			mesh.SetBuffer2f("uv0", uvVboData);

			mesh.SetIndices(indicesVboData, 0, Graphics.PrimitiveType.Triangles);

			MeshRenderer meshRenderer = sceneObject.GetModule<MeshRenderer>();
			if (meshRenderer)
			{
				meshRenderer.mesh = mesh;
			}
		}
Esempio n. 10
0
 public static Vector3f CrossProduct(Vector3f left, Vector3f right)
 {
     return new Vector3f(
         left.Y * right.Z - left.Z * right.Y,
         left.Z * right.X - left.X * right.Z,
         left.X * right.Y - left.Y * right.X);
 }
Esempio n. 11
0
    //Mouse drag, calculate rotation
    public void drag(Point NewPt, Quat4f NewRot)
    {
        //Map the point to the sphere
        this.mapToSphere(NewPt, EnVec);

        //Return the quaternion equivalent to the rotation
        if (NewRot != null)
        {
            Vector3f Perp = new Vector3f();

            //Compute the vector perpendicular to the begin and end vectors
            Vector3f.cross(Perp, StVec, EnVec);

            //Compute the length of the perpendicular vector
            if (Perp.length() > Epsilon)    //if its non-zero
            {
                //We're ok, so return the perpendicular vector as the transform after all
                NewRot.x = Perp.x;
                NewRot.y = Perp.y;
                NewRot.z = Perp.z;
                //In the quaternion values, w is cosine (theta / 2), where theta is rotation angle
                NewRot.w = Vector3f.dot(StVec, EnVec);
            }
            else                                    //if its zero
            {
                //The begin and end vectors coincide, so return an identity transform
                NewRot.x = NewRot.y = NewRot.z = NewRot.w = 0.0f;
            }
        }
    }
Esempio n. 12
0
        public static Matrix3f RotateAxis( Vector3f axis, float radians )
        {
            var normalizedAxis = axis.Normalized();
            float cosTheta = ( float )( Math.Cos( radians ) );
            float sinTheta = ( float )( Math.Sin( radians ) );

            float x = normalizedAxis.x;
            float y = normalizedAxis.y;
            float z = normalizedAxis.z;

            var m = new Matrix3f();

            m[ 0, 0 ] = x * x * ( 1.0f - cosTheta ) + cosTheta;
            m[ 0, 1 ] = y * x * ( 1.0f - cosTheta ) - z * sinTheta;
            m[ 0, 2 ] = z * x * ( 1.0f - cosTheta ) + y * sinTheta;

            m[ 1, 0 ] = x * y * ( 1.0f - cosTheta ) + z * sinTheta;
            m[ 1, 1 ] = y * y * ( 1.0f - cosTheta ) + cosTheta;
            m[ 1, 2 ] = z * y * ( 1.0f - cosTheta ) - x * sinTheta;

            m[ 2, 0 ] = x * z * ( 1.0f - cosTheta ) - y * sinTheta;
            m[ 2, 1 ] = y * z * ( 1.0f - cosTheta ) + x * sinTheta;
            m[ 2, 2 ] = z * z * ( 1.0f - cosTheta ) + cosTheta;

            return m;
        }
Esempio n. 13
0
        public static Matrix3f RotateBetween( Vector3f from, Vector3f to )
        {
            from.Normalize();
            to.Normalize();            

            var crossProduct = Vector3f.Cross( from, to );
            var normalizedAxis = crossProduct.Normalized();
            float sinTheta = crossProduct.Norm();
            float cosTheta = Vector3f.Dot( from, to );
            
            float x = normalizedAxis.x;
            float y = normalizedAxis.y;
            float z = normalizedAxis.z;
            
            var m = new Matrix3f();

            m[ 0, 0 ] = x * x * ( 1.0f - cosTheta ) + cosTheta;
            m[ 0, 1 ] = y * x * ( 1.0f - cosTheta ) - z * sinTheta;
            m[ 0, 2 ] = z * x * ( 1.0f - cosTheta ) + y * sinTheta;

            m[ 1, 0 ] = x * y * ( 1.0f - cosTheta ) + z * sinTheta;
            m[ 1, 1 ] = y * y * ( 1.0f - cosTheta ) + cosTheta;
            m[ 1, 2 ] = z * y * ( 1.0f - cosTheta ) - x * sinTheta;

            m[ 2, 0 ] = x * z * ( 1.0f - cosTheta ) - y * sinTheta;
            m[ 2, 1 ] = y * z * ( 1.0f - cosTheta ) + x * sinTheta;
            m[ 2, 2 ] = z * z * ( 1.0f - cosTheta ) + cosTheta;

            return m;
        }
Esempio n. 14
0
File: Fan.cs Progetto: Spritutu/ntxx
        /// <summary>
        /// 绘制风扇
        /// </summary>
        /// <param name="dxf"></param>
        /// <param name="startPoint">风扇起点,如果为横置,由左向右;如果为竖置,由下到上</param>
        /// <param name="endPoint">风扇终点,如果为横置,由左向右;如果为竖置,由下到上</param>
        /// <param name="pointerLocation">箭头位置,默认=0为无,=1代表箭头在中间,=2代表箭头在底部</param>
        public static void Draw(DxfDocument dxf, Vector3f startPoint, Vector3f endPoint,int pointerLocation=0)
        {
            Layer layer = new Layer("line");
            Line line = new Line(startPoint, endPoint);
            line.Layer = layer;
            dxf.AddEntity(line);

            //如果为横置
            if (startPoint.Y == endPoint.Y)
            {
                float segment = (endPoint.X - startPoint.X) / 4;
                Slash.Draw(dxf, new Location(startPoint.X + segment, startPoint.Y, startPoint.Z));
                Slash.Draw(dxf, new Location(startPoint.X + 2 * segment, startPoint.Y, startPoint.Z));
                Slash.Draw(dxf, new Location(startPoint.X + 3 * segment, startPoint.Y, startPoint.Z));
            }
            //如果为竖置
            else if (startPoint.X == endPoint.X)
            {
                float segment = (endPoint.Y - startPoint.Y) / 5;
                Slash.Draw(dxf, new Location(startPoint.X, startPoint.Y + segment, startPoint.Z));
                Slash.Draw(dxf, new Location(startPoint.X, startPoint.Y + 2 * segment, startPoint.Z));
                Slash.Draw(dxf, new Location(startPoint.X, startPoint.Y + 3 * segment, startPoint.Z));
                Slash.Draw(dxf, new Location(startPoint.X, startPoint.Y + 4 * segment, startPoint.Z));
                if (pointerLocation == 1)
                {
                    LinePointer.Draw(dxf,new Location(startPoint.X,(startPoint.Y+endPoint.Y)/2,startPoint.Z));
                }
                else if(pointerLocation==2)
                {
                    LinePointer.Draw(dxf, new Location(startPoint.X, startPoint.Y, startPoint.Z));
                }
            }
        }
Esempio n. 15
0
        public void SetVertices(Vector3f[] verts)
        {
            if (fVertexBufferObject != null)
            {
                fVertexBufferObject.Dispose();
                fVertexBufferObject = null;
            }


            // Write the vertex data to the buffer
            GCHandle dataPtr = GCHandle.Alloc(verts, GCHandleType.Pinned);
            int dataSize = Marshal.SizeOf(typeof(Vector3f)) * verts.Length;
            fVertexBufferObject = new VertexBufferObject(GI);
            fVertexBufferObject.Bind();
            fVertexBufferObject.Size = dataSize;
            
            try
            {
                fVertexBufferObject.Bind();
                fVertexBufferObject.Write(dataPtr.AddrOfPinnedObject(), 0, dataSize);
            }
            finally
            {
                fVertexBufferObject.Unbind();
                dataPtr.Free();
            }
       }
Esempio n. 16
0
 public void SetParameter(string Parameter, Vector3f[] vec3array)
 {
     for (int i = 0; i < vec3array.Length; i++)
     {
         this.SetParameter(Parameter + i, vec3array[i]);
     }
 }
Esempio n. 17
0
		public Transformation ()
		{
			translation = new Vector3f(0,0,0);
			scale = new Vector3f(1,1,1);
			rotation = Matrix3f.Identity();
			transformation = Matrix4f.Identity();
		}
Esempio n. 18
0
 public static bool SolidSphereHollowBox( Vector3f sphereCenter, float sphereRadius,
     Vector3f boxCorner, Vector3f boxSize )
 {
     float dmin = 0;
     var boxMax = boxCorner + boxSize;
     bool face = false;
     for( int i = 0; i < 3; ++i )
     {
         if( sphereCenter[ i ] < boxCorner[ i ] )
         {
             face = true;
             dmin += ( sphereCenter[ i ] - boxCorner[ i ] ) * ( sphereCenter[ i ] - boxCorner[ i ] );
         }
         else if( sphereCenter[ i ] > boxMax[ i ] )
         {
             face = true;
             dmin += ( sphereCenter[ i ] - boxMax[ i ] ) * ( sphereCenter[ i ] - boxMax[ i ] );
         }
         else if( sphereCenter[ i ] - boxCorner[ i ] <= sphereRadius )
         {
             face = true;
         }
         else if( boxMax[ i ] - sphereCenter[ i ] <= sphereRadius )
         {
             face = true;
         }
     }
     return ( face && ( dmin <= sphereRadius * sphereRadius ) );
 }
Esempio n. 19
0
        public void LoadBinaryData(byte[] inData)
        {
            using (MemoryStream ms = new MemoryStream(inData))
            {
                using (BinaryReader br = new BinaryReader(ms))
                {
                    this.WidthVertices = br.ReadUInt32();
                    this.HeightVertices = br.ReadUInt32();

                    this.WidthTileFlags = br.ReadUInt32();
                    this.HeightTileFlags = br.ReadUInt32();

                    this.Location = br.ReadVector3f();
                    this.MaterialIndex = br.ReadUInt16();

                    uint vertexCount = this.WidthVertices * this.HeightVertices;
                    for (int i = 0; i < vertexCount; ++i)
                    {
                        this.LiquidVertices.Add(new LiquidVertex(br.ReadBytes(LiquidVertex.GetSize())));
                    }

                    uint tileFlagCount = this.WidthTileFlags * this.HeightTileFlags;
                    for (int i = 0; i < tileFlagCount; ++i)
                    {
                        this.LiquidTileFlags.Add((LiquidFlags)br.ReadByte());
                    }
                }
            }
        }
Esempio n. 20
0
    public void mapToSphere(Point point, Vector3f vector)
    {
        //Copy paramter into temp point
        Point2f tempPoint = new Point2f(point.X, point.Y);

        //Adjust point coords and scale down to range of [-1 ... 1]
        tempPoint.x = (tempPoint.x * this.adjustWidth) - 1.0f;
        tempPoint.y = 1.0f - (tempPoint.y * this.adjustHeight);

        //Compute the square of the length of the vector to the point from the center
        float length = (tempPoint.x * tempPoint.x) + (tempPoint.y * tempPoint.y);

        //If the point is mapped outside of the sphere... (length > radius squared)
        if (length > 1.0f)
        {
            //Compute a normalizing factor (radius / sqrt(length))
            float norm = (float) (1.0 / Math.Sqrt(length));

            //Return the "normalized" vector, a point on the sphere
            vector.x = tempPoint.x * norm;
            vector.y = tempPoint.y * norm;
            vector.z = 0.0f;
        }
        else    //Else it's on the inside
        {
            //Return a vector to a point mapped inside the sphere sqrt(radius squared - length)
            vector.x = tempPoint.x;
            vector.y = tempPoint.y;
            vector.z = (float) Math.Sqrt(1.0f - length);
        }
    }
Esempio n. 21
0
        // TODO: get rid of ComputeProjectionMatrix()

        public Camera( Vector3f position, Vector3f forward, Vector3f up,
            float fovYDegrees,
            int screenWidth, int screenHeight )
        {
            FieldOfView = Arithmetic.DegreesToRadians( fovYDegrees );

            // interpolationKeyFrames = new KeyFrameInterpolator
            Frame = new ManipulatedCameraFrame();
            
            SceneRadius = 1.0f;
            orthoCoeff = ( float ) ( Math.Tan( FieldOfView / 2.0 ) );
            SceneCenter = Vector3f.Zero;

            CameraType = CameraType.PERSPECTIVE;

            ZNearCoefficient = 0.005f;
            ZClippingCoefficient = ( float ) ( Math.Sqrt( 3.0 ) );

            // dummy values
            screenSize = new Vector2i( screenWidth, screenHeight );

            Position = position;
            UpVector = up;
            ViewDirection = forward;

            ComputeViewMatrix();
            ComputeProjectionMatrix();
        }
Esempio n. 22
0
 public Vector3f AddStore(Vector3f other)
 {
     this.x += other.x;
     this.y += other.y;
     this.z += other.z;
     return this;
 }
Esempio n. 23
0
        private bool WithinArea(Vector3f location)
        {
            var differenceFromCenter = this.Position - location;
            var uLength = Util.Projection(differenceFromCenter, uDirection);
            var vLength = Util.Projection(differenceFromCenter, vDirection);

            return uLength.Magnitude() <= width / 2f && vLength.Magnitude() <= height / 2f;
        }
Esempio n. 24
0
        public void SetTranslationAndRotation( Vector3f translation, Quat4f rotation )
        {
            this.t_ = translation;
            this.q_ = rotation;

            // TODO:
            // emit modified
        }
 public VertexPosition3fNormal3fTexture2fColor4ub( Vector3f position, Vector3f normal,
     Vector2f uv, Vector4ub color )
 {
     this.position = position;
     this.normal = normal;
     this.textureCoordinates = uv;
     this.color = color;
 }
Esempio n. 26
0
 public Vector3f Add(Vector3f other)
 {
     Vector3f res = new Vector3f();
     res.x = this.x + other.x;
     res.y = this.y + other.y;
     res.z = this.z + other.z;
     return res;
 }
Esempio n. 27
0
 public Vertex(int tIndex, Vector3f tPosition)
 {
     index = tIndex;
     position = tPosition;
     connectedEdges = new List<Edge>();
     connectedFaces = new List<Face>();
     edgesAndFacesSorted = false;
 }
 public VertexPosition3fNormal3fTexture2f( float x, float y, float z,
     float nx, float ny, float nz,
     float u, float v )            
 {
     position = new Vector3f( x, y, z );
     normal = new Vector3f( nx, ny, nz );
     textureCoordinates = new Vector2f( u, v );
 }
Esempio n. 29
0
File: Vvd.cs Progetto: Frassle/Ibasa
 internal Vertex(ImmutableArray<BoneWeight> boneWeights,
     Vector3f position, Vector3f normal, Vector2f textureCoordinates, Vector4f tangent)
 {
     BoneWeights = boneWeights;
     Position = position;
     Normal = normal;
     TextureCoordinates = textureCoordinates;
     Tangent = tangent;
 }
Esempio n. 30
0
 /// <summary>
 /// Initializes a new instance of the <c>Polyline3dVertex</c> class.
 /// </summary>
 /// <param name="location">Polyline <see cref="Vector3f">vertex</see> coordinates.</param>
 public Polyline3dVertex(Vector3f location)
     : base(DxfObjectCode.Vertex)
 {
     this.flags = VertexTypeFlags.Polyline3dVertex;
     this.location = location;
     this.layer = Layer.Default;
     this.color = AciColor.ByLayer;
     this.lineType = LineType.ByLayer;
 }
Esempio n. 31
0
 public void SetRotation(Vector3f rotation)
 {
     Rotation = rotation;
     CalculateRotationMatrix();
 }
Esempio n. 32
0
 public Element RayTrace(Vector3f origin, Vector3f direction, float maxDistance)
 {
     return(null);
 }
Esempio n. 33
0
 /// <summary>
 /// Load this instance from the <see cref="System.String"/> representation.
 /// </summary>
 /// <param name="value">The <see cref="System.String"/> value to convert.</param>
 void ILoadFromString.FromString(string value)
 {
     string[] parts = value.Trim('[', ']').Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
     Row0 = Vector3f.Parse(parts[0]);
     Row1 = Vector3f.Parse(parts[1]);
 }
Esempio n. 34
0
        public virtual void formatMeasurement()
        {
            for (int i = count; --i >= 0;)
            {
                if (countPlusIndices[i + 1] < 0)
                {
                    strMeasurement = null;
                    return;
                }
            }
            if (count < 2)
            {
                return;
            }
            switch (count)
            {
            case 2:
                float distance = frame.getDistance(countPlusIndices[1], countPlusIndices[2]);
                strMeasurement = formatDistance(distance);
                break;

            case 3:
                float degrees = frame.getAngle(countPlusIndices[1], countPlusIndices[2], countPlusIndices[3]);
                strMeasurement = formatAngle(degrees);

                if (degrees == 180)
                {
                    aa       = null;
                    pointArc = null;
                }
                else
                {
                    Point3f pointA = getAtomPoint3f(1);
                    Point3f pointB = getAtomPoint3f(2);
                    Point3f pointC = getAtomPoint3f(3);

                    Vector3f vectorBA = new Vector3f();
                    Vector3f vectorBC = new Vector3f();
                    vectorBA.sub(pointA, pointB);
                    vectorBC.sub(pointC, pointB);
                    float radians = vectorBA.angle(vectorBC);

                    Vector3f vectorAxis = new Vector3f();
                    vectorAxis.cross(vectorBA, vectorBC);
                    aa = new AxisAngle4f(vectorAxis.x, vectorAxis.y, vectorAxis.z, radians);

                    vectorBA.normalize();
                    vectorBA.scale(0.5f);
                    pointArc = new Point3f(vectorBA);
                }

                break;

            case 4:
                float torsion = frame.getTorsion(countPlusIndices[1], countPlusIndices[2], countPlusIndices[3], countPlusIndices[4]);

                strMeasurement = formatAngle(torsion);
                break;

            default:
                System.Console.Out.WriteLine("Invalid count to measurement shape:" + count);
                throw new System.IndexOutOfRangeException();
            }
        }
Esempio n. 35
0
 public void ModifyAttachedCP(Vector3f vec, Angle angle)
 {
     AttachedCPData = new Tuple <Vector3f, Angle>(vec, angle);
 }
Esempio n. 36
0
        ///<summary>
        /// Gets the extreme point of the shape in world space in a given direction.
        ///</summary>
        ///<param name="direction">Direction to find the extreme point in.</param>
        /// <param name="shapeTransform">Transform to use for the shape.</param>
        ///<param name="extremePoint">Extreme point on the shape.</param>
        public void GetExtremePointWithoutMargin(Vector3f direction, ref RigidTransform shapeTransform, out Vector3f extremePoint)
        {
            Quaternion conjugate;

            Quaternion.Conjugate(ref shapeTransform.Orientation, out conjugate);
            Vector3f.Transform(ref direction, ref conjugate, out direction);
            GetLocalExtremePointWithoutMargin(ref direction, out extremePoint);

            Vector3f.Transform(ref extremePoint, ref shapeTransform.Orientation, out extremePoint);
            Vector3f.Add(ref extremePoint, ref shapeTransform.Position, out extremePoint);
        }
Esempio n. 37
0
 public void SetPosition(Vector3f position)
 {
     Position = position;
     CalculateTranslationMatrix();
 }
Esempio n. 38
0
 ///<summary>
 /// Gets the extreme point of the shape in local space in a given direction.
 ///</summary>
 ///<param name="direction">Direction to find the extreme point in.</param>
 ///<param name="extremePoint">Extreme point on the shape.</param>
 public abstract void GetLocalExtremePointWithoutMargin(ref Vector3f direction, out Vector3f extremePoint);
 public static extern Bool ovrp_SetOverlayQuad(Bool onTop, IntPtr texture, IntPtr device, Posef pose, Vector3f scale);
 public static bool SetOverlayQuad(bool onTop, bool headLocked, IntPtr texture, IntPtr device, Posef pose, Vector3f scale)
 {
     if (version >= v0110)
     {
         return(OVRP0110.ovrp_SetOverlayQuad2(ToBool(onTop), ToBool(headLocked), texture, device, pose, scale) == Bool.True);
     }
     else
     {
         return(OVRP0100.ovrp_SetOverlayQuad(ToBool(onTop), texture, device, pose, scale) == Bool.True);
     }
 }
Esempio n. 41
0
        private AnimatorStateMachine(AssetInfo assetInfo, AnimatorController controller, int stateMachineIndex) :
            base(assetInfo, 1)
        {
            VirtualSerializedFile virtualFile = (VirtualSerializedFile)assetInfo.File;

            LayerConstant layer = controller.Controller.GetLayerByStateMachineIndex(stateMachineIndex);

            Name = controller.TOS[layer.Binding];

            StateMachineConstant stateMachine = controller.Controller.StateMachineArray[stateMachineIndex].Instance;

            int stateCount        = stateMachine.StateConstantArray.Count;
            int stateMachineCount = 0;
            int count             = stateCount + stateMachineCount;
            int side = (int)Math.Ceiling(Math.Sqrt(count));

            List <AnimatorState> states = new List <AnimatorState>();

            m_childStates = new ChildAnimatorState[stateCount];
            for (int y = 0, stateIndex = 0; y < side && stateIndex < stateCount; y++)
            {
                for (int x = 0; x < side && stateIndex < stateCount; x++, stateIndex++)
                {
                    Vector3f           position   = new Vector3f(x * StateOffset, y * StateOffset, 0.0f);
                    AnimatorState      state      = AnimatorState.CreateVirtualInstance(virtualFile, controller, stateMachineIndex, stateIndex, position);
                    ChildAnimatorState childState = new ChildAnimatorState(state, position);
                    m_childStates[stateIndex] = childState;
                    states.Add(state);
                }
            }
            m_childStateMachines = new ChildAnimatorStateMachine[stateMachineCount];

            // set destination state for transitions here because all states has become valid only now
            for (int i = 0; i < stateMachine.StateConstantArray.Count; i++)
            {
                AnimatorState state         = states[i];
                StateConstant stateConstant = stateMachine.StateConstantArray[i].Instance;
                for (int j = 0; j < stateConstant.TransitionConstantArray.Count; j++)
                {
                    long stateTransitionPath                   = state.Transitions[j].PathID;
                    AnimatorStateTransition transition         = (AnimatorStateTransition)virtualFile.GetAsset(stateTransitionPath);
                    TransitionConstant      transitionConstant = stateConstant.TransitionConstantArray[j].Instance;
                    if (!transitionConstant.IsExit)
                    {
                        AnimatorState destState = states[transitionConstant.DestinationState];
                        transition.DstState = destState.File.CreatePPtr(destState);
                    }
                }
            }

            m_anyStateTransitions = new PPtr <AnimatorStateTransition> [stateMachine.AnyStateTransitionConstantArray.Count];
            for (int i = 0; i < stateMachine.AnyStateTransitionConstantArray.Count; i++)
            {
                TransitionConstant      transitionConstant = stateMachine.AnyStateTransitionConstantArray[i].Instance;
                AnimatorStateTransition transition         = AnimatorStateTransition.CreateVirtualInstance(virtualFile, controller, transitionConstant, states);
                m_anyStateTransitions[i] = transition.File.CreatePPtr(transition);
            }

            m_entryTransitions       = stateMachine.GetEntryTransitions(virtualFile, controller, layer.Binding, states);
            m_stateMachineBehaviours = new PPtr <MonoBehaviour> [0];

            AnyStatePosition           = new Vector3f(0.0f, -StateOffset, 0.0f);
            EntryPosition              = new Vector3f(StateOffset, -StateOffset, 0.0f);
            ExitPosition               = new Vector3f(2.0f * StateOffset, -StateOffset, 0.0f);
            ParentStateMachinePosition = new Vector3f(0.0f, -2.0f * StateOffset, 0.0f);

            DefaultState = ChildStates.Count > 0 ? ChildStates[stateMachine.DefaultState].State : default;
        }
Esempio n. 42
0
 public float DotProduct(Vector3f v)
 {
     return(x * v.x + y * v.y + z * v.z);
 }
Esempio n. 43
0
 public Vector3f Multiply(Vector3f v)
 {
     return(Multiply(v.x, v.y, v.z));
 }
Esempio n. 44
0
 public void SetScale(Vector3f scale)
 {
     Scale = scale;
     CalculateScaleMatrix();
 }
Esempio n. 45
0
 /// <summary>
 /// Computes a bounding box for the shape and expands it.
 /// </summary>
 /// <param name="transform">Transform to use to position the shape.</param>
 /// <param name="sweep">Extra to add to the bounding box.</param>
 /// <param name="boundingBox">Expanded bounding box.</param>
 public void GetSweptBoundingBox(ref RigidTransform transform, ref Vector3f sweep, out BoundingBox boundingBox)
 {
     GetBoundingBox(ref transform, out boundingBox);
     Toolbox.ExpandBoundingBox(ref boundingBox, ref sweep);
 }
Esempio n. 46
0
 static extern void sfSoundStream_setPosition(IntPtr SoundStream, Vector3f position);
Esempio n. 47
0
        ///<summary>
        /// Gets the extreme point of the shape in world space in a given direction with margin expansion.
        ///</summary>
        ///<param name="direction">Direction to find the extreme point in.</param>
        /// <param name="shapeTransform">Transform to use for the shape.</param>
        ///<param name="extremePoint">Extreme point on the shape.</param>
        public void GetExtremePoint(Vector3f direction, ref RigidTransform shapeTransform, out Vector3f extremePoint)
        {
            GetExtremePointWithoutMargin(direction, ref shapeTransform, out extremePoint);

            float directionLength = direction.LengthSquared;

            if (directionLength > MathHelper.Epsilon)
            {
                Vector3f.Multiply(ref direction, collisionMargin / (float)Math.Sqrt(directionLength), out direction);
                Vector3f.Add(ref extremePoint, ref direction, out extremePoint);
            }
        }
Esempio n. 48
0
 static public _OdGe.Vector3d ToHost(this Vector3f p)
 {
     return(new _OdGe.Vector3d(p.X, p.Y, p.Z));
 }
Esempio n. 49
0
        /// <summary>
        /// If go has a MeshFilter, extract it and append to SimpleMesh.
        /// Returns false if no filter.
        /// </summary>
        bool AppendGOMesh(GameObject go, SimpleMesh m, int[] vertexMap, FScene scene, int gid)
        {
            MeshFilter filter = go.GetComponent <MeshFilter>();

            if (filter == null || filter.mesh == null)
            {
                return(false);
            }

            Mesh curMesh = filter.sharedMesh;

            Vector3[] vertices = curMesh.vertices;
            Vector3[] normals  = (WriteNormals) ? curMesh.normals : null;
            Color[]   colors   = (WriteVertexColors) ? curMesh.colors : null;
            Vector2[] uvs      = (WriteUVs) ? curMesh.uv : null;

            if (vertexMap.Length < curMesh.vertexCount)
            {
                vertexMap = new int[curMesh.vertexCount * 2];
            }

            for (int i = 0; i < curMesh.vertexCount; ++i)
            {
                NewVertexInfo vi = new NewVertexInfo();
                vi.bHaveN = WriteNormals; vi.bHaveC = WriteVertexColors; vi.bHaveUV = WriteUVs;

                Vector3f v = vertices[i];
                // local to world
                v = filter.gameObject.transform.TransformPoint(v);
                // world back to scene
                v    = scene.ToSceneP(v);
                vi.v = MeshTransforms.FlipLeftRightCoordSystems(vi.v);

                if (WriteNormals)
                {
                    Vector3 n = normals[i];
                    n    = filter.gameObject.transform.TransformDirection(n); // to world
                    n    = scene.ToSceneN(n);                                 // to scene
                    vi.n = MeshTransforms.FlipLeftRightCoordSystems(vi.n);
                }
                if (WriteVertexColors)
                {
                    vi.c = colors[i];
                }
                if (WriteUVs)
                {
                    vi.uv = uvs[i];
                }

                vertexMap[i] = m.AppendVertex(vi);
            }

            int[] triangles  = curMesh.triangles;
            int   nTriangles = triangles.Length / 3;

            for (int i = 0; i < nTriangles; ++i)
            {
                int a = vertexMap[triangles[3 * i]];
                int b = vertexMap[triangles[3 * i + 1]];
                int c = vertexMap[triangles[3 * i + 2]];
                m.AppendTriangle(a, c, b, gid);  // TRI ORIENTATION IS REVERSED HERE!!
            }

            return(true);
        }
Esempio n. 50
0
 public void ModifyAttachedCP(DeepPointer ptr, Vector3f vec, Angle angle)
 {
     AttachedCPData = new CPData {
         CP_Pointer = ptr, SpawnPos = vec, SpawnAngle = angle
     };;
 }
Esempio n. 51
0
        /// <summary>
        /// Gets the bounding box of the convex shape transformed first into world space, and then into the local space of another affine transform.
        /// </summary>
        /// <param name="shapeTransform">Transform to use to put the shape into world space.</param>
        /// <param name="spaceTransform">Used as the frame of reference to compute the bounding box.
        /// In effect, the shape is transformed by the inverse of the space transform to compute its bounding box in local space.</param>
        /// <param name="sweep">Vector to expand the bounding box with in local space.</param>
        /// <param name="boundingBox">Bounding box in the local space.</param>
        public void GetSweptLocalBoundingBox(ref RigidTransform shapeTransform, ref AffineTransform spaceTransform, ref Vector3f sweep, out BoundingBox boundingBox)
        {
            GetLocalBoundingBox(ref shapeTransform, ref spaceTransform, out boundingBox);
            Vector3f expansion;

            Vector3f.TransformTranspose(ref sweep, ref spaceTransform.LinearTransform, out expansion);
            Toolbox.ExpandBoundingBox(ref boundingBox, ref expansion);
        }
Esempio n. 52
0
        public virtual ExportStatus Export(FScene scene, string filename)
        {
            int[]            vertexMap = new int[2048]; // temp
            List <WriteMesh> vMeshes   = new List <WriteMesh>();

            if (WriteFaceGroups)
            {
                throw new Exception("SceneMeshExporter.Export: writing face groups has not yet been implemented!");
            }

            // extract all the mesh data we want to export
            foreach (SceneObject so in scene.SceneObjects)
            {
                if (so.IsTemporary || so.IsSurface == false || SceneUtil.IsVisible(so) == false)
                {
                    continue;
                }
                if (SOFilterF != null && SOFilterF(so) == false)
                {
                    continue;
                }

                // if this SO has an internal mesh we can just copy, use it
                if (so is DMeshSO)
                {
                    DMeshSO meshSO = so as DMeshSO;

                    // todo: flags

                    // make a copy of mesh
                    DMesh3 m = GetMeshForDMeshSO(meshSO);

                    // transform to scene coords and swap left/right
                    foreach (int vid in m.VertexIndices())
                    {
                        Vector3f v = (Vector3f)m.GetVertex(vid);
                        v = SceneTransforms.ObjectToSceneP(meshSO, v);
                        v = MeshTransforms.FlipLeftRightCoordSystems(v);
                        m.SetVertex(vid, v);
                    }
                    m.ReverseOrientation();

                    vMeshes.Add(new WriteMesh(m, so.Name));
                }


                // Look for lower-level fGameObject items to export. By default
                // this is anything with a MeshFilter, override CollectGOChildren
                // or use GOFilterF to add restrictions
                List <fGameObject> vExports = CollectGOChildren(so);
                if (vExports.Count > 0)
                {
                    SimpleMesh m = new SimpleMesh();
                    m.Initialize(WriteNormals, WriteVertexColors, WriteUVs, WriteFaceGroups);
                    int groupCounter = 1;

                    foreach (fGameObject childgo in vExports)
                    {
                        if (GOFilterF != null && GOFilterF(so, childgo) == false)
                        {
                            continue;
                        }

                        if (AppendGOMesh(childgo, m, vertexMap, scene, groupCounter))
                        {
                            groupCounter++;
                        }
                    }

                    vMeshes.Add(new WriteMesh(m, so.Name));
                }
            }


            // ok, we are independent of Scene now and can write in bg thread
            if (WriteInBackgroundThreads)
            {
                ExportStatus status = new ExportStatus()
                {
                    Exporter = this, IsComputing = true
                };
                WriteOptions useOptions = Options;
                useOptions.ProgressFunc = (cur, max) => {
                    status.Progress    = cur;
                    status.MaxProgress = max;
                };
                BackgroundWriteThread t = new BackgroundWriteThread()
                {
                    Meshes      = vMeshes, options = useOptions, Filename = filename,
                    CompletionF = (result) => {
                        LastWriteStatus         = result.code;
                        LastErrorMessage        = result.message;
                        status.LastErrorMessage = result.message;
                        status.Ok          = (result.code == IOCode.Ok);
                        status.IsComputing = false;
                        if (BackgroundWriteCompleteF != null)
                        {
                            BackgroundWriteCompleteF(this, status);
                        }
                    }
                };
                t.Start();
                return(status);
            }
            else
            {
                IOWriteResult result = StandardMeshWriter.WriteFile(filename, vMeshes, Options);
                LastWriteStatus  = result.code;
                LastErrorMessage = result.message;
                return(new ExportStatus()
                {
                    Exporter = this, IsComputing = false,
                    Ok = (result.code == IOCode.Ok),
                    LastErrorMessage = result.message
                });
            }
        }
Esempio n. 53
0
 /// <summary>
 /// Constructs a new constraint which restricts two degrees of linear freedom and two degrees of angular freedom between two entities.
 /// </summary>
 /// <param name="connectionA">First entity of the constraint pair.</param>
 /// <param name="connectionB">Second entity of the constraint pair.</param>
 /// <param name="lineAnchor">Location of the anchor for the line to be attached to connectionA in world space.</param>
 /// <param name="lineDirection">Axis in world space to be attached to connectionA along which connectionB can move and rotate.</param>
 /// <param name="pointAnchor">Location of the anchor for the point to be attached to connectionB in world space.</param>
 public LineSliderJoint(Entity connectionA, Entity connectionB, Vector3f lineAnchor, Vector3f lineDirection, Vector3f pointAnchor)
 {
     if (connectionA == null)
     {
         connectionA = TwoEntityConstraint.WorldEntity;
     }
     if (connectionB == null)
     {
         connectionB = TwoEntityConstraint.WorldEntity;
     }
     PointOnLineJoint = new PointOnLineJoint(connectionA, connectionB, lineAnchor, lineDirection, pointAnchor);
     AngularJoint     = new RevoluteAngularJoint(connectionA, connectionB, lineDirection);
     Limit            = new LinearAxisLimit(connectionA, connectionB, lineAnchor, pointAnchor, lineDirection, 0, 0);
     Motor            = new LinearAxisMotor(connectionA, connectionB, lineAnchor, pointAnchor, lineDirection);
     Limit.IsActive   = false;
     Motor.IsActive   = false;
     Add(PointOnLineJoint);
     Add(AngularJoint);
     Add(Limit);
     Add(Motor);
 }
Esempio n. 54
0
        private ARImageNode CreateImageNode(ImageInfo imageInfo, Quaternion orientation, Vector3f scale, Vector3f position)
        {
            // ノードを作成
            var texture   = CreateTexture2D(imageInfo);
            var imageNode = new ARImageNode(texture);

            // 回転およびスケーリング
            imageNode.Orientation = orientation;
            imageNode.Scale       = scale;
            imageNode.Position    = position;

            return(imageNode);
        }
 public static Vector3f Copy(this Vector3f s)
 {
     return(new Vector3f(s.x, s.y, s.z));
 }
Esempio n. 56
0
            public Bitmap AsImage(Model Parent, float scaleX = 1, float scaleY = 1, float scaleZ = 1, int rx = 0, int ry = 0, int rz = 0, bool wireframe = false, uint defaultcolour = 0xFFFFFFFF)
            {
                buffer = new Bitmap(512, 512);

                int x = 256, y = 256;

                rx &= 0xFF;
                Matrix rotateX = new Matrix(
                    1, 0, 0,
                    0, (float)MyCos[rx], (float)MySin[rx],
                    0, (float)-MySin[rx], (float)MyCos[rx]);

                ry &= 0xFF;
                Matrix rotateY = new Matrix(
                    (float)MyCos[ry], 0, (float)-MySin[ry],
                    0, 1, 0,
                    (float)MySin[ry], 0, (float)MyCos[ry]);

                rz &= 0xFF;
                Matrix rotateZ = new Matrix(
                    (float)MyCos[rz], (float)-MySin[rz], 0,
                    (float)MySin[rz], (float)MyCos[rz], 0,
                    0, 0, 1);

                Matrix transform = rotateX.Multiply(rotateY).Multiply(rotateZ);

                int size = 512 * 512;

                double[] zBuffer = new double[size];
                for (int q = 0; q < size; q++)
                {
                    zBuffer[q] = -9999999999.9f;
                }

                int wHalf = 512 / 2;
                int hHalf = 512 / 2;

                int FaceID = 0;

                for (int i = 0; i < Parent.Faces.Count; i += Parent.FaceVerticiesCount, FaceID++)
                {
                    int[] face = new int[Parent.FaceVerticiesCount];

                    for (int f = 0; f < Parent.FaceVerticiesCount; f++)
                    {
                        face[f] = Parent.Faces[i + f];
                    }

                    uint colour = defaultcolour;

                    if (Parent.HasColours)
                    {
                        colour = (uint)((255 << 24) + (Parent.Colours[Parent.Faces[i]].r << 16) + (Parent.Colours[Parent.Faces[i]].g << 8) + Parent.Colours[Parent.Faces[i]].b);
                    }

                    Vector3f xv = new Vector3f();
                    Vector3f yv = new Vector3f();
                    Vector3f zv = new Vector3f();

                    if (Parent.FaceVerticiesCount == 4 && !wireframe)
                    {
                        xv = new Vector3f(Vertices[face[0]].x, Vertices[face[0]].y, Vertices[face[0]].z);
                        yv = new Vector3f(Vertices[face[2]].x, Vertices[face[2]].y, Vertices[face[2]].z);
                        zv = new Vector3f(Vertices[face[3]].x, Vertices[face[3]].y, Vertices[face[3]].z);

                        Vector3f q_v1 = transform.Transform(xv).Multiply(scaleX, scaleY, scaleZ);
                        Vector3f q_v2 = transform.Transform(yv).Multiply(scaleX, scaleY, scaleZ);
                        Vector3f q_v3 = transform.Transform(zv).Multiply(scaleX, scaleY, scaleZ);

                        // Offset model
                        q_v1.x += x;
                        q_v1.y += y;
                        q_v2.x += x;
                        q_v2.y += y;
                        q_v3.x += x;
                        q_v3.y += y;

                        Vector3f q_n1 = transform.Transform(Vertices[face[0]].normal.Normalize());
                        Vector3f q_n2 = transform.Transform(Vertices[face[2]].normal.Normalize());
                        Vector3f q_n3 = transform.Transform(Vertices[face[3]].normal.Normalize());

                        Vector3f q_varying_intensity = new Vector3f();
                        Vector3f q_lightdir          = new Vector3f(0.0f, -1.0f, 0.0f);

                        q_varying_intensity.x = Math.Max(0.0f, q_lightdir.DotProduct(q_n1));
                        q_varying_intensity.y = Math.Max(0.0f, q_lightdir.DotProduct(q_n2));
                        q_varying_intensity.z = Math.Max(0.0f, q_lightdir.DotProduct(q_n3));

                        double q_intensity = q_varying_intensity.Distance();

                        int q_minX = (int)Math.Max(0.0, Math.Ceiling(Math.Min(q_v1.x, Math.Min(q_v2.x, q_v3.x))));
                        int q_maxX = (int)Math.Min(wHalf * 2 - 1.0, Math.Floor(Math.Max(q_v1.x, Math.Max(q_v2.x, q_v3.x))));
                        int q_minY = (int)Math.Max(0.0, Math.Ceiling(Math.Min(q_v1.y, Math.Min(q_v2.y, q_v3.y))));
                        int q_maxY = (int)Math.Min(hHalf * 2 - 1.0, Math.Floor(Math.Max(q_v1.y, Math.Max(q_v2.y, q_v3.y))));

                        double triangleArea = (q_v1.y - q_v3.y) * (q_v2.x - q_v3.x) + (q_v2.y - q_v3.y) * (q_v3.x - q_v1.x);

                        for (int q_y = q_minY; q_y <= q_maxY; q_y++)
                        {
                            for (int q_x = q_minX; q_x <= q_maxX; q_x++)
                            {
                                double b1 = ((q_y - q_v3.y) * (q_v2.x - q_v3.x) + (q_v2.y - q_v3.y) * (q_v3.x - q_x)) / triangleArea;
                                double b2 = ((q_y - q_v1.y) * (q_v3.x - q_v1.x) + (q_v3.y - q_v1.y) * (q_v1.x - q_x)) / triangleArea;
                                double b3 = ((q_y - q_v2.y) * (q_v1.x - q_v2.x) + (q_v1.y - q_v2.y) * (q_v2.x - q_x)) / triangleArea;
                                if (b1 >= 0 && b1 <= 1 && b2 >= 0 && b2 <= 1 && b3 >= 0 && b3 <= 1)
                                {
                                    double depth = b1 * q_v1.z + b2 * q_v2.z + b3 * q_v3.z;

                                    q_intensity = (double)q_varying_intensity.DotProduct((float)b1, (float)b2, (float)b3);

                                    int zIndex = q_y * wHalf * 2 + q_x;
                                    if (zBuffer[zIndex] < depth)
                                    {
                                        if (q_intensity > 0.5)
                                        {
                                            System.Drawing.Color c = System.Drawing.Color.FromArgb(0xFF, System.Drawing.Color.FromArgb((int)ColourBlend(colour, 0xFFFFFF, q_intensity * 2.0 - 1.0)));
                                            buffer.SetPixel(q_x, q_y, c);
                                        }
                                        else
                                        {
                                            System.Drawing.Color c = System.Drawing.Color.FromArgb(0xFF, System.Drawing.Color.FromArgb((int)ColourBlend(colour, 0x000000, (0.5 - q_intensity))));
                                            buffer.SetPixel(q_x, q_y, c);
                                        }
                                        zBuffer[zIndex] = depth;
                                    }
                                }
                            }
                        }
                    }

                    xv = new Vector3f(Vertices[face[0]].x, Vertices[face[0]].y, Vertices[face[0]].z);
                    yv = new Vector3f(Vertices[face[1]].x, Vertices[face[1]].y, Vertices[face[1]].z);
                    zv = new Vector3f(Vertices[face[2]].x, Vertices[face[2]].y, Vertices[face[2]].z);

                    Vector3f v1 = transform.Transform(xv).Multiply(scaleX, scaleY, scaleZ);
                    Vector3f v2 = transform.Transform(yv).Multiply(scaleX, scaleY, scaleZ);
                    Vector3f v3 = transform.Transform(zv).Multiply(scaleX, scaleY, scaleZ);

                    // Offset model
                    v1.x += x;
                    v1.y += y;
                    v2.x += x;
                    v2.y += y;
                    v3.x += x;
                    v3.y += y;

                    Vector3f n1 = transform.Transform(Vertices[face[0]].normal.Normalize());
                    Vector3f n2 = transform.Transform(Vertices[face[1]].normal.Normalize());
                    Vector3f n3 = transform.Transform(Vertices[face[1]].normal.Normalize());

                    Vector3f varying_intensity = new Vector3f();
                    Vector3f lightdir          = new Vector3f(0.0f, -1.0f, 0.0f);

                    varying_intensity.x = Math.Max(0.0f, lightdir.DotProduct(n1));
                    varying_intensity.y = Math.Max(0.0f, lightdir.DotProduct(n2));
                    varying_intensity.z = Math.Max(0.0f, lightdir.DotProduct(n3));

                    double intensity;

                    int minX = (int)Math.Max(0.0, Math.Ceiling(Math.Min(v1.x, Math.Min(v2.x, v3.x))));
                    int maxX = (int)Math.Min(wHalf * 2 - 1.0, Math.Floor(Math.Max(v1.x, Math.Max(v2.x, v3.x))));
                    int minY = (int)Math.Max(0.0, Math.Ceiling(Math.Min(v1.y, Math.Min(v2.y, v3.y))));
                    int maxY = (int)Math.Min(hHalf * 2 - 1.0, Math.Floor(Math.Max(v1.y, Math.Max(v2.y, v3.y))));

                    if (wireframe)
                    {
                        intensity = Math.Min(1.0, Math.Max(0.0, varying_intensity.Distance()));

                        if (intensity > 0.5)
                        {
                            DrawLine((int)v1.x, (int)v1.y, (int)v2.x, (int)v2.y, ColourBlend(colour, 0xFFFFFF, intensity * 2.0 - 1.0));
                            DrawLine((int)v3.x, (int)v3.y, (int)v2.x, (int)v2.y, ColourBlend(colour, 0xFFFFFF, intensity * 2.0 - 1.0));
                        }
                        else
                        {
                            DrawLine((int)v1.x, (int)v1.y, (int)v2.x, (int)v2.y, ColourBlend(colour, 0x000000, (0.5 - intensity)));
                            DrawLine((int)v3.x, (int)v3.y, (int)v2.x, (int)v2.y, ColourBlend(colour, 0x000000, (0.5 - intensity)));
                        }
                    }
                    else
                    {
                        double triangleArea = (v1.y - v3.y) * (v2.x - v3.x) + (v2.y - v3.y) * (v3.x - v1.x);

                        for (int t_y = minY; t_y <= maxY; t_y++)
                        {
                            for (int t_x = minX; t_x <= maxX; t_x++)
                            {
                                double b1 = ((t_y - v3.y) * (v2.x - v3.x) + (v2.y - v3.y) * (v3.x - t_x)) / triangleArea;
                                double b2 = ((t_y - v1.y) * (v3.x - v1.x) + (v3.y - v1.y) * (v1.x - t_x)) / triangleArea;
                                double b3 = ((t_y - v2.y) * (v1.x - v2.x) + (v1.y - v2.y) * (v2.x - t_x)) / triangleArea;
                                if (b1 >= 0 && b1 <= 1 && b2 >= 0 && b2 <= 1 && b3 >= 0 && b3 <= 1)
                                {
                                    double depth = b1 * v1.z + b2 * v2.z + b3 * v3.z;
                                    // b1, b2, b3 make up "bar"; a Vector3

                                    // fragment
                                    intensity = varying_intensity.DotProduct((float)b1, (float)b2, (float)b3);

                                    int zIndex = t_y * wHalf * 2 + t_x;
                                    if (zBuffer[zIndex] < depth)
                                    {
                                        if (intensity > 0.5)
                                        {
                                            System.Drawing.Color c = System.Drawing.Color.FromArgb(0xFF, System.Drawing.Color.FromArgb((int)ColourBlend(colour, 0xFFFFFF, intensity * 2.0 - 1.0)));
                                            buffer.SetPixel(t_x, t_y, c);
                                        }
                                        else
                                        {
                                            System.Drawing.Color c = System.Drawing.Color.FromArgb(0xFF, System.Drawing.Color.FromArgb((int)ColourBlend(colour, 0x000000, (0.5 - intensity))));
                                            buffer.SetPixel(t_x, t_y, c);
                                        }
                                        zBuffer[zIndex] = depth;
                                    }
                                }
                            }
                        }
                    }
                }

                return(buffer);
            }
Esempio n. 57
0
 override public void SetLocalScale(Vector3f scale)
 {
     target.SetLocalScale(scale);
 }
Esempio n. 58
0
 abstract public void SetLocalScale(Vector3f scale);
Esempio n. 59
0
 public override void manipulate(Particle particle, Vector3f deltaVelocity, Color4f deltaColor, ref float deltaLife)
 {
     deltaVelocity.set(particle.velocity);
     deltaVelocity.stretch(strength);
     deltaVelocity.invert();
 }
Esempio n. 60
0
        /// <summary>
        /// SV_movestep
        /// Called by monster program code.
        /// The move will be adjusted for slopes and stairs, but if the move isn't
        /// possible, no move is done, false is returned, and
        /// pr_global_struct.trace_normal is set to the normal of the blocking wall
        /// </summary>
        public Boolean MoveStep(MemoryEdict ent, ref Vector3f move, Boolean relink)
        {
            Trace_t trace;

            // try the move
            var      oldorg = ent.v.origin;
            Vector3f neworg;

            MathLib.VectorAdd(ref ent.v.origin, ref move, out neworg);

            // flying monsters don't step up
            if ((( Int32 )ent.v.flags & (EdictFlags.FL_SWIM | EdictFlags.FL_FLY)) != 0)
            {
                // try one move with vertical motion, then one without
                for (var i = 0; i < 2; i++)
                {
                    MathLib.VectorAdd(ref ent.v.origin, ref move, out neworg);
                    var enemy = ProgToEdict(ent.v.enemy);
                    if (i == 0 && enemy != sv.edicts[0])
                    {
                        var dz = ent.v.origin.z - enemy.v.origin.z;
                        if (dz > 40)
                        {
                            neworg.z -= 8;
                        }
                        if (dz < 30)
                        {
                            neworg.z += 8;
                        }
                    }

                    trace = Move(ref ent.v.origin, ref ent.v.mins, ref ent.v.maxs, ref neworg, 0, ent);
                    if (trace.fraction == 1)
                    {
                        if ((( Int32 )ent.v.flags & EdictFlags.FL_SWIM) != 0 &&
                            PointContents(ref trace.endpos) == ( Int32 )Q1Contents.Empty)
                        {
                            return(false);                              // swim monster left water
                        }
                        MathLib.Copy(ref trace.endpos, out ent.v.origin);
                        if (relink)
                        {
                            LinkEdict(ent, true);
                        }
                        return(true);
                    }

                    if (enemy == sv.edicts[0])
                    {
                        break;
                    }
                }

                return(false);
            }

            // push down from a step height above the wished position
            neworg.z += STEPSIZE;
            var end = neworg;

            end.z -= STEPSIZE * 2;

            trace = Move(ref neworg, ref ent.v.mins, ref ent.v.maxs, ref end, 0, ent);

            if (trace.allsolid)
            {
                return(false);
            }

            if (trace.startsolid)
            {
                neworg.z -= STEPSIZE;
                trace     = Move(ref neworg, ref ent.v.mins, ref ent.v.maxs, ref end, 0, ent);
                if (trace.allsolid || trace.startsolid)
                {
                    return(false);
                }
            }
            if (trace.fraction == 1)
            {
                // if monster had the ground pulled out, go ahead and fall
                if ((( Int32 )ent.v.flags & EdictFlags.FL_PARTIALGROUND) != 0)
                {
                    MathLib.VectorAdd(ref ent.v.origin, ref move, out ent.v.origin);
                    if (relink)
                    {
                        LinkEdict(ent, true);
                    }
                    ent.v.flags = ( Int32 )ent.v.flags & ~EdictFlags.FL_ONGROUND;
                    return(true);
                }

                return(false);                      // walked off an edge
            }

            // check point traces down for dangling corners
            MathLib.Copy(ref trace.endpos, out ent.v.origin);

            if (!CheckBottom(ent))
            {
                if ((( Int32 )ent.v.flags & EdictFlags.FL_PARTIALGROUND) != 0)
                {
                    // entity had floor mostly pulled out from underneath it
                    // and is trying to correct
                    if (relink)
                    {
                        LinkEdict(ent, true);
                    }
                    return(true);
                }
                ent.v.origin = oldorg;
                return(false);
            }

            if ((( Int32 )ent.v.flags & EdictFlags.FL_PARTIALGROUND) != 0)
            {
                ent.v.flags = ( Int32 )ent.v.flags & ~EdictFlags.FL_PARTIALGROUND;
            }
            ent.v.groundentity = EdictToProg(trace.ent);

            // the move is ok
            if (relink)
            {
                LinkEdict(ent, true);
            }
            return(true);
        }