コード例 #1
0
ファイル: Mesh.cs プロジェクト: optimus-code/Q2Sharp
        public virtual System.Boolean R_CullAliasModel(entity_t e)
        {
            qfiles.dmdl_t paliashdr = (qfiles.dmdl_t)currentmodel.extradata;
            if ((e.frame >= paliashdr.num_frames) || (e.frame < 0))
            {
                VID.Printf(Defines.PRINT_ALL, "R_CullAliasModel " + currentmodel.name + ": no such frame " + e.frame + '\\');
                e.frame = 0;
            }

            if ((e.oldframe >= paliashdr.num_frames) || (e.oldframe < 0))
            {
                VID.Printf(Defines.PRINT_ALL, "R_CullAliasModel " + currentmodel.name + ": no such oldframe " + e.oldframe + '\\');
                e.oldframe = 0;
            }

            qfiles.daliasframe_t pframe    = paliashdr.aliasFrames[e.frame];
            qfiles.daliasframe_t poldframe = paliashdr.aliasFrames[e.oldframe];
            if (pframe == poldframe)
            {
                for (var i = 0; i < 3; i++)
                {
                    mins[i] = pframe.translate[i];
                    maxs[i] = mins[i] + pframe.scale[i] * 255;
                }
            }
            else
            {
                Single thismaxs, oldmaxs;
                for (var i = 0; i < 3; i++)
                {
                    thismaxs = pframe.translate[i] + pframe.scale[i] * 255;
                    oldmaxs  = poldframe.translate[i] + poldframe.scale[i] * 255;
                    if (pframe.translate[i] < poldframe.translate[i])
                    {
                        mins[i] = pframe.translate[i];
                    }
                    else
                    {
                        mins[i] = poldframe.translate[i];
                    }
                    if (thismaxs > oldmaxs)
                    {
                        maxs[i] = thismaxs;
                    }
                    else
                    {
                        maxs[i] = oldmaxs;
                    }
                }
            }

            Single[] tmp;
            for (var i = 0; i < 8; i++)
            {
                tmp = bbox[i];
                if ((i & 1) != 0)
                {
                    tmp[0] = mins[0];
                }
                else
                {
                    tmp[0] = maxs[0];
                }
                if ((i & 2) != 0)
                {
                    tmp[1] = mins[1];
                }
                else
                {
                    tmp[1] = maxs[1];
                }
                if ((i & 4) != 0)
                {
                    tmp[2] = mins[2];
                }
                else
                {
                    tmp[2] = maxs[2];
                }
            }

            tmp = mins;
            Math3D.VectorCopy(e.angles, tmp);
            tmp[YAW] = -tmp[YAW];
            Math3D.AngleVectors(tmp, vectors[0], vectors[1], vectors[2]);
            for (var i = 0; i < 8; i++)
            {
                Math3D.VectorCopy(bbox[i], tmp);
                bbox[i][0] = Math3D.DotProduct(vectors[0], tmp);
                bbox[i][1] = -Math3D.DotProduct(vectors[1], tmp);
                bbox[i][2] = Math3D.DotProduct(vectors[2], tmp);
                Math3D.VectorAdd(e.origin, bbox[i], bbox[i]);
            }

            Int32 f, mask;
            var   aggregatemask = ~0;

            for (var p = 0; p < 8; p++)
            {
                mask = 0;
                for (f = 0; f < 4; f++)
                {
                    var dp = Math3D.DotProduct(frustum[f].normal, bbox[p]);
                    if ((dp - frustum[f].dist) < 0)
                    {
                        mask |= (1 << f);
                    }
                }

                aggregatemask &= mask;
            }

            if (aggregatemask != 0)
            {
                return(true);
            }

            return(false);
        }
コード例 #2
0
        public void ViewChanged(DoubleVector lookDirection)
        {
            if (_marker2D != null)
            {
                _viewport.Children.Remove(_marker2D);
            }

            if (_marker2D == null)
            {
                _marker2D           = new ScreenSpaceLines3D();
                _marker2D.Color     = UtilityWPF.ColorFromHex("60A0A0A0");
                _marker2D.Thickness = 4d;
            }

            _marker2D.Clear();

            RotateTransform3D transform = new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRotation(new DoubleVector(0, 0, 1, 0, -1, 0), lookDirection)));

            #region Marker 2D

            double orthDist   = (_sizeMult * _field.Size * 1.1d) / 2d;
            double cornerDist = (_sizeMult * _field.Size * .2d) / 2d;

            // TopLeft
            Point3D  corner    = transform.Transform(new Point3D(-orthDist, -orthDist, -orthDist));
            Vector3D direction = transform.Transform(new Vector3D(cornerDist, 0, 0));
            _marker2D.AddLine(corner, corner + direction);
            direction = transform.Transform(new Vector3D(0, cornerDist, 0));
            _marker2D.AddLine(corner, corner + direction);

            //TopRight
            corner    = transform.Transform(new Point3D(orthDist, -orthDist, -orthDist));
            direction = transform.Transform(new Vector3D(-cornerDist, 0, 0));
            _marker2D.AddLine(corner, corner + direction);
            direction = transform.Transform(new Vector3D(0, cornerDist, 0));
            _marker2D.AddLine(corner, corner + direction);

            //BottomRight
            corner    = transform.Transform(new Point3D(orthDist, orthDist, -orthDist));
            direction = transform.Transform(new Vector3D(-cornerDist, 0, 0));
            _marker2D.AddLine(corner, corner + direction);
            direction = transform.Transform(new Vector3D(0, -cornerDist, 0));
            _marker2D.AddLine(corner, corner + direction);

            //BottomLeft
            corner    = transform.Transform(new Point3D(-orthDist, orthDist, -orthDist));
            direction = transform.Transform(new Vector3D(cornerDist, 0, 0));
            _marker2D.AddLine(corner, corner + direction);
            direction = transform.Transform(new Vector3D(0, -cornerDist, 0));
            _marker2D.AddLine(corner, corner + direction);

            _viewport.Children.Add(_marker2D);

            #endregion

            // Camera
            _camera.Position      = transform.Transform(new Point3D(0, 0, (_sizeMult * _field.Size * -4d) / 2d));
            _camera.LookDirection = lookDirection.Standard;
            _camera.UpDirection   = lookDirection.Orth;

            // Remember it
            _lookDirection = lookDirection;
        }
コード例 #3
0
        private void DrawLines_Plate(int numSamples, double half, double lineThickness, AxisFor axisX, AxisFor axisY, AxisFor axisZ)
        {
            const double ELAPSEDURATIONSECONDS = 1;

            // Figure out how wide to make the plate
            int totalSamples  = numSamples * numSamples * numSamples;       // numsamples is per axis, so cube it
            int cellsPerSlice = _field.Size * _field.Size;
            int numSlices     = Convert.ToInt32(Math.Round(Convert.ToDouble(totalSamples) / Convert.ToDouble(cellsPerSlice)));

            if (numSlices == 0)
            {
                numSlices = 1;
            }

            int toOffset   = numSlices / 2;
            int fromOffset = numSlices - toOffset - 1;

            DateTime now = DateTime.UtcNow;

            bool isOverField = false;

            if (_mousePoint != null)
            {
                #region Snap to mouse

                // Cast a ray (Copied this from ItemSelectDragLogic.ChangeDragPlane, DragItem)

                Point3D point = new Point3D(0, 0, 0);

                RayHitTestParameters cameraLookCenter = UtilityWPF.RayFromViewportPoint(_camera, _viewport, new Point(_viewport.ActualWidth * .5d, _viewport.ActualHeight * .5d));

                // Come up with a snap plane
                Vector3D  standard = Math3D.GetArbitraryOrhonganal(cameraLookCenter.Direction);
                Vector3D  orth     = Vector3D.CrossProduct(standard, cameraLookCenter.Direction);
                ITriangle plane    = new Triangle(point, point + standard, point + orth);

                DragHitShape dragPlane = new DragHitShape();
                dragPlane.SetShape_Plane(plane);

                // Cast a ray onto that plane from the current mouse position
                RayHitTestParameters mouseRay = UtilityWPF.RayFromViewportPoint(_camera, _viewport, _mousePoint.Value);
                Point3D?hitPoint = dragPlane.CastRay(mouseRay);

                if (hitPoint != null)
                {
                    // Find the nearest Z cell
                    double halfSize = (_field.Size * _sizeMult) / 2d;
                    double cellSize = (_field.Size * _sizeMult) / _field.Size;

                    int zIndex = Convert.ToInt32((halfSize - axisZ.GetValue(hitPoint.Value)) / cellSize);

                    if (zIndex >= 0 && zIndex < _field.Size)
                    {
                        isOverField = true;

                        // Cap to field
                        _plateCurrentIndex = _field.Size - zIndex;        // it's actually the opposite
                        if (_plateCurrentIndex - fromOffset < 0)
                        {
                            _plateCurrentIndex = fromOffset;
                        }
                        else if (_plateCurrentIndex + toOffset > _field.Size - 1)
                        {
                            _plateCurrentIndex = _field.Size - toOffset - 1;
                        }

                        _sceneRemaining = now + TimeSpan.FromSeconds(ELAPSEDURATIONSECONDS);
                    }
                }

                #endregion
            }

            if (!isOverField)
            {
                #region Shift the plate

                if (_plateCurrentIndex + toOffset > _field.Size - 1)
                {
                    _plateCurrentIndex = _field.Size - toOffset - 1;
                    _sceneRemaining    = now + TimeSpan.FromSeconds(ELAPSEDURATIONSECONDS);
                }
                else if (now > _sceneRemaining)
                {
                    _plateCurrentIndex--;

                    if (_plateCurrentIndex - fromOffset <= 0)
                    {
                        _plateCurrentIndex = _field.Size - toOffset - 1;
                    }

                    _sceneRemaining = now + TimeSpan.FromSeconds(ELAPSEDURATIONSECONDS);
                }

                #endregion
            }

            double[] velX = _field.VelocityX;
            double[] velY = _field.VelocityY;
            double[] velZ = _field.VelocityZ;

            bool[] blocked = _field.Blocked;

            _velocityLines.BeginAddingLines();

            for (int z = _plateCurrentIndex - fromOffset; z <= _plateCurrentIndex + toOffset; z++)
            {
                for (int x = 0; x < _field.Size; x++)
                {
                    for (int y = 0; y < _field.Size; y++)
                    {
                        int xRef = -1;
                        int yRef = -1;
                        int zRef = -1;

                        axisX.Set3DIndex(ref xRef, ref yRef, ref zRef, x);
                        axisY.Set3DIndex(ref xRef, ref yRef, ref zRef, y);
                        axisZ.Set3DIndex(ref xRef, ref yRef, ref zRef, z);

                        int index1D = _field.Get1DIndex(xRef, yRef, zRef);

                        if (blocked[index1D])
                        {
                            continue;
                        }

                        DrawLinesSprtAddLine(xRef, yRef, zRef, index1D, half, lineThickness, velX, velY, velZ);
                    }
                }
            }

            _velocityLines.EndAddingLines();
        }
コード例 #4
0
        private void glControl_Paint(object sender, PaintEventArgs e)
        {
            Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);
            Gl.glLoadIdentity();

            // Setup wireframe or solid fill drawing mode
            if (Wireframe)
            {
                Gl.glPolygonMode(Gl.GL_FRONT_AND_BACK, Gl.GL_LINE);
            }
            else
            {
                Gl.glPolygonMode(Gl.GL_FRONT, Gl.GL_FILL);
            }

            Vector3 center = Vector3.Zero;

            Glu.gluLookAt(
                center.X, (double)scrollZoom.Value * 0.1d + center.Y, center.Z,
                center.X, center.Y, center.Z,
                0d, 0d, 1d);

            // Push the world matrix
            Gl.glPushMatrix();

            Gl.glEnableClientState(Gl.GL_VERTEX_ARRAY);
            Gl.glEnableClientState(Gl.GL_TEXTURE_COORD_ARRAY);

            // World rotations
            Gl.glRotatef((float)scrollRoll.Value, 1f, 0f, 0f);
            Gl.glRotatef((float)scrollPitch.Value, 0f, 1f, 0f);
            Gl.glRotatef((float)scrollYaw.Value, 0f, 0f, 1f);

            if (Prims != null)
            {
                for (int i = 0; i < Prims.Count; i++)
                {
                    Primitive prim = Prims[i].Prim;

                    if (i == cboPrim.SelectedIndex)
                    {
                        Gl.glColor3f(1f, 0f, 0f);
                    }
                    else
                    {
                        Gl.glColor3f(1f, 1f, 1f);
                    }

                    // Individual prim matrix
                    Gl.glPushMatrix();

                    // The root prim position is sim-relative, while child prim positions are
                    // parent-relative. We want to apply parent-relative translations but not
                    // sim-relative ones
                    if (Prims[i].Prim.ParentID != 0)
                    {
                        // Apply prim translation and rotation
                        Gl.glMultMatrixf(Math3D.CreateTranslationMatrix(prim.Position));
                        Gl.glMultMatrixf(Math3D.CreateRotationMatrix(prim.Rotation));
                    }

                    // Prim scaling
                    Gl.glScalef(prim.Scale.X, prim.Scale.Y, prim.Scale.Z);

                    // Draw the prim faces
                    for (int j = 0; j < Prims[i].Faces.Count; j++)
                    {
                        if (i == cboPrim.SelectedIndex)
                        {
                            // This prim is currently selected in the dropdown
                            //Gl.glColor3f(0f, 1f, 0f);
                            Gl.glColor3f(1f, 1f, 1f);

                            if (j == cboFace.SelectedIndex)
                            {
                                // This face is currently selected in the dropdown
                            }
                            else
                            {
                                // This face is not currently selected in the dropdown
                            }
                        }
                        else
                        {
                            // This prim is not currently selected in the dropdown
                            Gl.glColor3f(1f, 1f, 1f);
                        }

                        #region Texturing

                        Face     face = Prims[i].Faces[j];
                        FaceData data = (FaceData)face.UserData;

                        if (data.TexturePointer != 0)
                        {
                            // Set the color to solid white so the texture is not altered
                            //Gl.glColor3f(1f, 1f, 1f);
                            // Enable texturing for this face
                            Gl.glEnable(Gl.GL_TEXTURE_2D);
                        }
                        else
                        {
                            Gl.glDisable(Gl.GL_TEXTURE_2D);
                        }

                        // Bind the texture
                        Gl.glBindTexture(Gl.GL_TEXTURE_2D, data.TexturePointer);

                        #endregion Texturing

                        Gl.glTexCoordPointer(2, Gl.GL_FLOAT, 0, data.TexCoords);
                        Gl.glVertexPointer(3, Gl.GL_FLOAT, 0, data.Vertices);
                        Gl.glDrawElements(Gl.GL_TRIANGLES, data.Indices.Length, Gl.GL_UNSIGNED_SHORT, data.Indices);
                    }

                    // Pop the prim matrix
                    Gl.glPopMatrix();
                }
            }

            // Pop the world matrix
            Gl.glPopMatrix();

            Gl.glDisableClientState(Gl.GL_TEXTURE_COORD_ARRAY);
            Gl.glDisableClientState(Gl.GL_VERTEX_ARRAY);

            Gl.glFlush();
        }
コード例 #5
0
        private static Model3D[] CreateIcons_Translate(double lineRadius, double lineThickness, double arrowThickness, double sphereRadius)
        {
            #region define points

            Vector[] cores1 = new[]
            {
                new Vector(1, 0),
                new Vector(0, 1),
                new Vector(-1, 0),
                new Vector(0, -1),
            };

            var cores2 = cores1.
                         Select(o =>
                                (
                                    o * lineThickness / 2,
                                    o * lineRadius * 2d / 3d,
                                    o * lineRadius
                                )).
                         ToArray();

            var lines = cores2.
                        Select(o => new
            {
                from = Math3D.ProjectPointOntoSphere(o.Item1.X, o.Item1.Y, sphereRadius),
                to   = Math3D.ProjectPointOntoSphere(o.Item2.X, o.Item2.Y, sphereRadius),
                tip  = Math3D.ProjectPointOntoSphere(o.Item3.X, o.Item3.Y, sphereRadius),
                bar  = GetLinePoints(o.Item1, o.Item2, lineThickness, arrowThickness, sphereRadius),
            }).
                        ToArray();

            Point3D origin = Math3D.ProjectPointOntoSphere(0, 0, sphereRadius);

            #endregion
            #region create triangles

            List <Triangle> triangles = new List <Triangle>();

            foreach (var line in lines)
            {
                triangles.Add(new Triangle(origin, line.bar.fromRight, line.bar.fromLeft));

                triangles.Add(new Triangle(line.bar.fromLeft, line.bar.fromRight, line.bar.toRight));
                triangles.Add(new Triangle(line.bar.toRight, line.bar.toLeft, line.bar.fromLeft));

                triangles.Add(new Triangle(line.bar.baseLeft, line.bar.toLeft, line.tip));
                triangles.Add(new Triangle(line.bar.toLeft, line.bar.toRight, line.tip));
                triangles.Add(new Triangle(line.bar.toRight, line.bar.baseRight, line.tip));
            }

            ITriangleIndexed[] indexedTriangles = TriangleIndexed.ConvertToIndexed(triangles.ToArray());

            #endregion

            List <Model3D> retVal = new List <Model3D>();

            MaterialGroup material = new MaterialGroup();
            material.Children.Add(new DiffuseMaterial(new SolidColorBrush(WorldColors.ImpulseEngine_Icon_Color)));
            material.Children.Add(WorldColors.ImpulseEngine_Icon_Specular);
            material.Children.Add(WorldColors.ImpulseEngine_Icon_Emissive);

            foreach (Transform3D transform in GetRotations_Tetrahedron(sphereRadius))
            {
                GeometryModel3D geometry = new GeometryModel3D();
                geometry.Material     = material;
                geometry.BackMaterial = material;
                geometry.Geometry     = UtilityWPF.GetMeshFromTriangles(indexedTriangles);
                geometry.Transform    = transform;

                retVal.Add(geometry);
            }

            return(retVal.ToArray());
        }
コード例 #6
0
ファイル: MobjManager.cs プロジェクト: UnclePunch/HSDLib
        /// <summary>
        ///
        /// </summary>
        /// <param name="mobj"></param>
        public void BindMOBJ(Shader shader, HSD_MOBJ mobj, HSD_JOBJ parentJOBJ, MatAnimManager animation)
        {
            if (mobj == null)
            {
                return;
            }

            GL.Enable(EnableCap.Texture2D);

            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);

            GL.Enable(EnableCap.AlphaTest);
            GL.AlphaFunc(AlphaFunction.Greater, 0f);

            GL.DepthMask(!mobj.RenderFlags.HasFlag(RENDER_MODE.NO_ZUPDATE));

            // Pixel Processing
            shader.SetInt("alphaOp", -1);   // none
            shader.SetInt("alphaComp0", 7); // always
            shader.SetInt("alphaComp1", 7);

            var pp = mobj.PEDesc;

            if (pp != null)
            {
                GL.BlendFunc(GXTranslator.toBlendingFactor(pp.SrcFactor), GXTranslator.toBlendingFactor(pp.DstFactor));
                GL.DepthFunc(GXTranslator.toDepthFunction(pp.DepthFunction));

                shader.SetInt("alphaOp", (int)pp.AlphaOp);
                shader.SetInt("alphaComp0", (int)pp.AlphaComp0);
                shader.SetInt("alphaComp1", (int)pp.AlphaComp1);
                shader.SetFloat("alphaRef0", pp.AlphaRef0 / 255f);
                shader.SetFloat("alphaRef1", pp.AlphaRef1 / 255f);
            }


            // Materials
            var color = mobj.Material;

            if (color != null)
            {
                if (animation != null)
                {
                    color = animation.GetMaterialState(mobj);
                }

                shader.SetVector4("ambientColor", color.AMB_R / 255f, color.AMB_G / 255f, color.AMB_B / 255f, color.AMB_A / 255f);
                shader.SetVector4("diffuseColor", color.DIF_R / 255f, color.DIF_G / 255f, color.DIF_B / 255f, color.DIF_A / 255f);
                shader.SetVector4("specularColor", color.SPC_R / 255f, color.SPC_G / 255f, color.SPC_B / 255f, color.SPC_A / 255f);
                shader.SetFloat("shinniness", color.Shininess);
                shader.SetFloat("alpha", color.Alpha);
            }

            var enableAll = mobj.RenderFlags.HasFlag(RENDER_MODE.DF_ALL);

            shader.SetBoolToInt("no_zupdate", mobj.RenderFlags.HasFlag(RENDER_MODE.NO_ZUPDATE));
            shader.SetBoolToInt("enableSpecular", parentJOBJ.Flags.HasFlag(JOBJ_FLAG.SPECULAR) && mobj.RenderFlags.HasFlag(RENDER_MODE.SPECULAR));
            shader.SetBoolToInt("enableDiffuse", parentJOBJ.Flags.HasFlag(JOBJ_FLAG.LIGHTING) && mobj.RenderFlags.HasFlag(RENDER_MODE.DIFFUSE));
            shader.SetBoolToInt("useConstant", mobj.RenderFlags.HasFlag(RENDER_MODE.CONSTANT));
            shader.SetBoolToInt("useVertexColor", mobj.RenderFlags.HasFlag(RENDER_MODE.VERTEX));

            // Textures
            for (int i = 0; i < MAX_TEX; i++)
            {
                shader.SetBoolToInt($"hasTEX[{i}]", mobj.RenderFlags.HasFlag(RENDER_MODE.TEX0 + (i << 4)) || enableAll);
            }

            shader.SetInt("BumpTexture", -1);

            //LoadTextureConstants(shader);

            // these are always uniform
            GL.Uniform1(GL.GetUniformLocation(shader.programId, "textures"), 4, new int[] { 0, 1, 2, 3 });

            // Bind Textures
            if (mobj.Textures != null)
            {
                var textures = mobj.Textures.List;
                for (int i = 0; i < textures.Count; i++)
                {
                    if (i > MAX_TEX)
                    {
                        break;
                    }

                    var tex        = textures[i];
                    var displayTex = tex;

                    if (tex.ImageData == null)
                    {
                        continue;
                    }

                    var blending = tex.Blending;

                    var transform = Matrix4.CreateScale(tex.SX, tex.SY, tex.SZ) *
                                    Matrix4.CreateFromQuaternion(Math3D.FromEulerAngles(tex.RZ, tex.RY, tex.RX)) *
                                    Matrix4.CreateTranslation(tex.TX, tex.TY, tex.TZ);

                    if (tex.SY != 0 && tex.SX != 0 && tex.SZ != 0)
                    {
                        transform.Invert();
                    }

                    if (animation != null)
                    {
                        var state = animation.GetTextureAnimState(tex);
                        if (state != null)
                        {
                            displayTex = state.TOBJ;
                            blending   = state.Blending;
                            transform  = state.Transform;
                        }
                    }

                    // make sure texture is loaded
                    PreLoadTexture(displayTex);

                    // grab texture id
                    var texid = TextureManager.Get(imageBufferTextureIndex[displayTex.ImageData.ImageData]);

                    // set texture
                    GL.ActiveTexture(TextureUnit.Texture0 + i);
                    GL.BindTexture(TextureTarget.Texture2D, texid);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)GXTranslator.toWrapMode(tex.WrapS));
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)GXTranslator.toWrapMode(tex.WrapT));
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)GXTranslator.toMagFilter(tex.MagFilter));

                    var wscale = tex.WScale;
                    var hscale = tex.HScale;

                    var mirrorX = tex.WrapS == GXWrapMode.MIRROR;
                    var mirrorY = tex.WrapT == GXWrapMode.MIRROR;

                    var flags = tex.Flags;

                    int coordType = (int)flags & 0xF;
                    int colorOP   = ((int)flags >> 16) & 0xF;
                    int alphaOP   = ((int)flags >> 20) & 0xF;

                    if (flags.HasFlag(TOBJ_FLAGS.BUMP))
                    {
                        colorOP = 4;
                    }

                    shader.SetBoolToInt($"TEX[{i}].is_ambient", flags.HasFlag(TOBJ_FLAGS.LIGHTMAP_AMBIENT));
                    shader.SetBoolToInt($"TEX[{i}].is_diffuse", flags.HasFlag(TOBJ_FLAGS.LIGHTMAP_DIFFUSE));
                    shader.SetBoolToInt($"TEX[{i}].is_specular", flags.HasFlag(TOBJ_FLAGS.LIGHTMAP_SPECULAR));
                    shader.SetBoolToInt($"TEX[{i}].is_ext", flags.HasFlag(TOBJ_FLAGS.LIGHTMAP_EXT));
                    shader.SetBoolToInt($"TEX[{i}].is_bump", flags.HasFlag(TOBJ_FLAGS.BUMP));
                    shader.SetInt($"TEX[{i}].color_operation", colorOP);
                    shader.SetInt($"TEX[{i}].alpha_operation", alphaOP);
                    shader.SetInt($"TEX[{i}].coord_type", coordType);
                    shader.SetFloat($"TEX[{i}].blend", blending);
                    shader.SetBoolToInt($"TEX[{i}].mirror_fix", mirrorY);
                    shader.SetVector2($"TEX[{i}].uv_scale", wscale, hscale);
                    shader.SetMatrix4x4($"TEX[{i}].transform", ref transform);

                    var  tev    = tex.TEV;
                    bool useTev = tev != null && tev.active.HasFlag(TOBJ_TEVREG_ACTIVE.COLOR_TEV);
                    shader.SetBoolToInt($"hasTev[{i}]", useTev);
                    if (useTev)
                    {
                        shader.SetInt($"Tev[{i}].color_op", (int)tev.color_op);
                        shader.SetInt($"Tev[{i}].color_bias", (int)tev.color_bias);
                        shader.SetInt($"Tev[{i}].color_scale", (int)tev.color_scale);
                        shader.SetBoolToInt($"Tev[{i}].color_clamp", tev.color_clamp);
                        shader.SetInt($"Tev[{i}].color_a", (int)tev.color_a_in);
                        shader.SetInt($"Tev[{i}].color_b", (int)tev.color_b_in);
                        shader.SetInt($"Tev[{i}].color_c", (int)tev.color_c_in);
                        shader.SetInt($"Tev[{i}].color_d", (int)tev.color_d_in);

                        shader.SetInt($"Tev[{i}].alpha_op", (int)tev.alpha_op);
                        shader.SetInt($"Tev[{i}].alpha_bias", (int)tev.alpha_bias);
                        shader.SetInt($"Tev[{i}].alpha_scale", (int)tev.alpha_scale);
                        shader.SetBoolToInt($"Tev[{i}].alpha_clamp", tev.alpha_clamp);
                        shader.SetInt($"Tev[{i}].alpha_a", (int)tev.alpha_a_in);
                        shader.SetInt($"Tev[{i}].alpha_b", (int)tev.alpha_b_in);
                        shader.SetInt($"Tev[{i}].alpha_c", (int)tev.alpha_c_in);
                        shader.SetInt($"Tev[{i}].alpha_d", (int)tev.alpha_d_in);

                        shader.SetColor($"Tev[{i}].konst", tev.constant, tev.constantAlpha);
                        shader.SetColor($"Tev[{i}].tev0", tev.tev0, tev.tev0Alpha);
                        shader.SetColor($"Tev[{i}].tev1", tev.tev1, tev.tev1Alpha);
                    }
                }
            }
        }
コード例 #7
0
ファイル: Form1.cs プロジェクト: Mexahoid/CSF
 public Cube(int side, Math3D.Point3D origin)
 {
     width = side;
     height = side;
     depth = side;
     cubeOrigin = origin;
 }
コード例 #8
0
        public static bool FindTarget(edict_t self)
        {
            edict_t client;
            bool    heardit;
            int     r;

            if ((self.monsterinfo.aiflags & Defines.AI_GOOD_GUY) != 0)
            {
                if (self.goalentity != null && self.goalentity.inuse && self.goalentity.classname != null)
                {
                    if (self.goalentity.classname.Equals("target_actor"))
                    {
                        return(false);
                    }
                }

                return(false);
            }

            if ((self.monsterinfo.aiflags & Defines.AI_COMBAT_POINT) != 0)
            {
                return(false);
            }
            heardit = false;
            if ((GameBase.level.sight_entity_framenum >= (GameBase.level.framenum - 1)) && 0 == (self.spawnflags & 1))
            {
                client = GameBase.level.sight_entity;
                if (client.enemy == self.enemy)
                {
                    return(false);
                }
            }
            else if (GameBase.level.sound_entity_framenum >= (GameBase.level.framenum - 1))
            {
                client  = GameBase.level.sound_entity;
                heardit = true;
            }
            else if (null != (self.enemy) && (GameBase.level.sound2_entity_framenum >= (GameBase.level.framenum - 1)) && 0 != (self.spawnflags & 1))
            {
                client  = GameBase.level.sound2_entity;
                heardit = true;
            }
            else
            {
                client = GameBase.level.sight_client;
                if (client == null)
                {
                    return(false);
                }
            }

            if (!client.inuse)
            {
                return(false);
            }
            if (client.client != null)
            {
                if ((client.flags & Defines.FL_NOTARGET) != 0)
                {
                    return(false);
                }
            }
            else if ((client.svflags & Defines.SVF_MONSTER) != 0)
            {
                if (client.enemy == null)
                {
                    return(false);
                }
                if ((client.enemy.flags & Defines.FL_NOTARGET) != 0)
                {
                    return(false);
                }
            }
            else if (heardit)
            {
                if ((client.owner.flags & Defines.FL_NOTARGET) != 0)
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
            if (!heardit)
            {
                r = Range(self, client);
                if (r == Defines.RANGE_FAR)
                {
                    return(false);
                }
                if (client.light_level <= 5)
                {
                    return(false);
                }
                if (!Visible(self, client))
                {
                    return(false);
                }
                if (r == Defines.RANGE_NEAR)
                {
                    if (client.show_hostile < GameBase.level.time && !Infront(self, client))
                    {
                        return(false);
                    }
                }
                else if (r == Defines.RANGE_MID)
                {
                    if (!Infront(self, client))
                    {
                        return(false);
                    }
                }

                if (client == self.enemy)
                {
                    return(true);
                }
                self.enemy = client;
                if (!self.enemy.classname.Equals("player_noise"))
                {
                    self.monsterinfo.aiflags &= ~Defines.AI_SOUND_TARGET;
                    if (self.enemy.client == null)
                    {
                        self.enemy = self.enemy.enemy;
                        if (self.enemy.client == null)
                        {
                            self.enemy = null;
                            return(false);
                        }
                    }
                }
            }
            else
            {
                float[] temp = new float[] { 0, 0, 0 };
                if ((self.spawnflags & 1) != 0)
                {
                    if (!Visible(self, client))
                    {
                        return(false);
                    }
                }
                else
                {
                    if (!GameBase.gi.InPHS(self.s.origin, client.s.origin))
                    {
                        return(false);
                    }
                }

                Math3D.VectorSubtract(client.s.origin, self.s.origin, temp);
                if (Math3D.VectorLength(temp) > 1000)
                {
                    return(false);
                }
                if (client.areanum != self.areanum)
                {
                    if (!GameBase.gi.AreasConnected(self.areanum, client.areanum))
                    {
                        return(false);
                    }
                }
                self.ideal_yaw = Math3D.Vectoyaw(temp);
                M.M_ChangeYaw(self);
                self.monsterinfo.aiflags |= Defines.AI_SOUND_TARGET;
                if (client == self.enemy)
                {
                    return(true);
                }
                self.enemy = client;
            }

            FoundTarget(self);
            if (0 == (self.monsterinfo.aiflags & Defines.AI_SOUND_TARGET) && (self.monsterinfo.sight != null))
            {
                self.monsterinfo.sight.Interact(self, self.enemy);
            }
            return(true);
        }
コード例 #9
0
            public override bool Think(edict_t self)
            {
                float[] spot1 = new float[] { 0, 0, 0 };
                float[] spot2 = new float[] { 0, 0, 0 };
                float   chance;
                trace_t tr;

                if (self.enemy.health > 0)
                {
                    Math3D.VectorCopy(self.s.origin, spot1);
                    spot1[2] += self.viewheight;
                    Math3D.VectorCopy(self.enemy.s.origin, spot2);
                    spot2[2] += self.enemy.viewheight;
                    tr        = GameBase.gi.Trace(spot1, null, null, spot2, self, Defines.CONTENTS_SOLID | Defines.CONTENTS_MONSTER | Defines.CONTENTS_SLIME | Defines.CONTENTS_LAVA | Defines.CONTENTS_WINDOW);
                    if (tr.ent != self.enemy)
                    {
                        return(false);
                    }
                }

                if (GameAI.enemy_range == Defines.RANGE_MELEE)
                {
                    if (GameBase.skill.value == 0 && (Lib.Rand() & 3) != 0)
                    {
                        return(false);
                    }
                    if (self.monsterinfo.melee != null)
                    {
                        self.monsterinfo.attack_state = Defines.AS_MELEE;
                    }
                    else
                    {
                        self.monsterinfo.attack_state = Defines.AS_MISSILE;
                    }
                    return(true);
                }

                if (self.monsterinfo.attack == null)
                {
                    return(false);
                }
                if (GameBase.level.time < self.monsterinfo.attack_finished)
                {
                    return(false);
                }
                if (GameAI.enemy_range == Defines.RANGE_FAR)
                {
                    return(false);
                }
                if ((self.monsterinfo.aiflags & Defines.AI_STAND_GROUND) != 0)
                {
                    chance = 0.4F;
                }
                else if (GameAI.enemy_range == Defines.RANGE_MELEE)
                {
                    chance = 0.2F;
                }
                else if (GameAI.enemy_range == Defines.RANGE_NEAR)
                {
                    chance = 0.1F;
                }
                else if (GameAI.enemy_range == Defines.RANGE_MID)
                {
                    chance = 0.02F;
                }
                else
                {
                    return(false);
                }

                if (GameBase.skill.value == 0)
                {
                    chance *= 0.5f;
                }
                else if (GameBase.skill.value >= 2)
                {
                    chance *= 2;
                }
                if (Lib.Random() < chance)
                {
                    self.monsterinfo.attack_state    = Defines.AS_MISSILE;
                    self.monsterinfo.attack_finished = GameBase.level.time + 2 * Lib.Random();
                    return(true);
                }

                if ((self.flags & Defines.FL_FLY) != 0)
                {
                    if (Lib.Random() < 0.3F)
                    {
                        self.monsterinfo.attack_state = Defines.AS_SLIDING;
                    }
                    else
                    {
                        self.monsterinfo.attack_state = Defines.AS_STRAIGHT;
                    }
                }

                return(false);
            }
コード例 #10
0
ファイル: Euler.cs プロジェクト: Mexahoid/CSF
 public Model3D()
 {
     Points = new Math3D.Point3D[0];
       Edges = new Edge3D[0];
       Mathes = new Math3D();
       Cam = new Math3D.Camera();
       Polygons = new Polygon3D[0];
       PLength = ELength = RLength = 0;
 }
コード例 #11
0
    public override void AdjustPose()
    {
        TFSession.Runner runner = session.GetRunner();

        //Assume model is trained with body x and z positions and y rotation normalized to that of the head
        //Assume model is trained with right hand coordinate system

        //Pivot the head and hands in the y-axis around the head such that the head's y rotation is 0
        Vector3 rotationPoint  = head.position;
        float   headRotation   = head.rotation.eulerAngles.y;
        float   rotationAmount = headRotation;

        TransformInfo pivotedHead      = Math3D.PivotY(head, rotationPoint, rotationAmount);
        TransformInfo pivotedHandLeft  = Math3D.PivotY(hand_left, rotationPoint, rotationAmount);
        TransformInfo pivotedHandRight = Math3D.PivotY(hand_right, rotationPoint, rotationAmount);

        //pivoted_head.position = pivotedHead.position;
        //pivoted_head.rotation = pivotedHead.rotation;

        //pivoted_left.position = pivotedHandLeft.position;
        //pivoted_left.rotation = pivotedHandLeft.rotation;

        //pivoted_right.position = pivotedHandRight.position;
        //pivoted_right.rotation = pivotedHandRight.rotation;

        //Convert rotations to right hand coordinate system
        //Quaternion convertedHeadRotation = Math3D.RightToLeftHand (pivotedHead.rotation.x, pivotedHead.rotation.y, pivotedHead.rotation.z, pivotedHead.rotation.w);
        //Quaternion convertedLeftHandRotation = Math3D.RightToLeftHand (pivotedHead.rotation.x, pivotedHead.rotation.y, pivotedHead.rotation.z, pivotedHead.rotation.w);
        //Quaternion convertedRightHandRotation = Math3D.RightToLeftHand (pivotedHead.rotation.x, pivotedHead.rotation.y, pivotedHead.rotation.z, pivotedHead.rotation.w);
        Quaternion pivotedHeadRotation      = pivotedHead.rotation;
        Quaternion pivotedLeftHandRotation  = pivotedHandLeft.rotation;
        Quaternion pivotedRightHandRotation = pivotedHandRight.rotation;

        float[,] inputs = new float[, ] {
            {
                pivotedHeadRotation.x,
                pivotedHeadRotation.y,
                pivotedHeadRotation.z,
                pivotedHeadRotation.w,
                0,
                pivotedHead.position.y *scalingFactor,
                0,
                pivotedLeftHandRotation.x,
                pivotedLeftHandRotation.y,
                pivotedLeftHandRotation.z,
                pivotedLeftHandRotation.w,
                pivotedHandLeft.position.x *scalingFactor,
                pivotedHandLeft.position.y *scalingFactor,
                pivotedHandLeft.position.z *scalingFactor,
                pivotedRightHandRotation.x,
                pivotedRightHandRotation.y,
                pivotedRightHandRotation.z,
                pivotedRightHandRotation.w,
                pivotedHandRight.position.x *scalingFactor,
                pivotedHandRight.position.y *scalingFactor,
                pivotedHandRight.position.z *scalingFactor
            }
        };

        runner.AddInput(graph [inputLayer] [0], inputs);
        runner.Fetch(graph[outputLayer][0]);
        float[,] output_tensor = runner.Run() [0].GetValue() as float[, ];
        float x = output_tensor [0, 0];
        float y = output_tensor [0, 1];
        float z = output_tensor [0, 2];
        float w = 1 - x * x - y * y - z * z;

        if (w < 0)
        {
            bodyTransform.position = head.position + positionOffset;
            Quaternion newRotation = Quaternion.Euler(new Vector3(0, head.rotation.eulerAngles.y));
            bodyTransform.rotation = newRotation;
            return;
        }
        w = Mathf.Sqrt(w);

        bodyTransform.rotation = Math3D.RightToLeftHand(x, y, z, w);
        bodyTransform.Rotate(new Vector3(0, headRotation));
        // position the body such that the base of the neck is right under the head
        bodyTransform.position = bodyTransform.position + head.position - neck.position + positionOffset;
    }
コード例 #12
0
ファイル: Renderer.cs プロジェクト: alexbasic/SimpleRender
        private void DrawTriangle(Vertex v1, Vertex v2, Vertex v3)
        {
            //var v1 = primitive.Vertices[triangle.Vertex1];
            //var v2 = primitive.Vertices[triangle.Vertex2];
            //var v3 = primitive.Vertices[triangle.Vertex3];

            var vec1 = new Vector4(v1.X, v1.Y, v1.Z, 1);
            var vec2 = new Vector4(v2.X, v2.Y, v2.Z, 1);
            var vec3 = new Vector4(v3.X, v3.Y, v3.Z, 1);

            Vector3f faceNormal = Math3D.CalculateNormal(Math3D.ConvertToDecart(vec1), Math3D.ConvertToDecart(vec2), Math3D.ConvertToDecart(vec3));

            var worldCoord1 = _modelMatrix * new Vector4(v1.X, v1.Y, v1.Z, 1);
            var worldCoord2 = _modelMatrix * new Vector4(v2.X, v2.Y, v2.Z, 1);
            var worldCoord3 = _modelMatrix * new Vector4(v3.X, v3.Y, v3.Z, 1);

            ShaderProgram.ComputeVertex(new VertexInput {
                Position = new Vector4(v1.X, v1.Y, v1.Z, 1), Normal = (Vector4)faceNormal
            });
            ShaderProgram.ComputeVertex(new VertexInput {
                Position = new Vector4(v1.X, v1.Y, v1.Z, 1), Normal = (Vector4)faceNormal
            });
            ShaderProgram.ComputeVertex(new VertexInput {
                Position = new Vector4(v1.X, v1.Y, v1.Z, 1), Normal = (Vector4)faceNormal
            });

            Draw3D.SimpleRasterizeTriangle(
                ConvertToScreenCoord0(decartvector1),
                ConvertToScreenCoord0(decartvector2),
                ConvertToScreenCoord0(decartvector3),
                FrameBuffer,
                Color.FromArgb((int)(255 * Restrict(sampleColor.X)), (int)(255 * Restrict(sampleColor.Y)), (int)(255 * Restrict(sampleColor.Z))),
                _zBuffer);
        }
コード例 #13
0
        /// <summary>
        /// Shifts the spline with <paramref name="amount"/> distance and returns a new spline
        /// </summary>
        /// <param name="safeDist">
        /// The max distance between the middle of the curves and their extreme points.
        /// If your shifted curve has too many sharp edges try pumping this number up.
        /// But beware because it causes it to have more points and thus decreasing performance.
        /// </param>
        /// <param name="newSpline">If you want the returned spline to be put into an already existing spline assign this parameter.</param>
        public BezierSpline GetShiftedSpline(float amount, float safeDist = 0.3f, BezierSpline newSpline = null)
        {
            BezierSpline _shiftedSpline;

            if (newSpline != null)
            {
                _shiftedSpline = newSpline;
            }
            else
            {
                _shiftedSpline = new GameObject().AddComponent <BezierSpline>();
            }
            _shiftedSpline.Clear();
            _shiftedSpline.name = "Lane" + amount;

            // So, you cannot offset a Bézier curve perfectly with another Bézier curve, no matter how high-order you make that
            // other Bézier curve. However, we can chop up a curve into "safe" sub-curves (where safe means that all the control
            // points are always on a single side of the baseline, and the midpoint of the curve at t=0.5 is roughly in the centre
            // of the polygon defined by the curve coordinates) and then point-scale each sub-curve with respect to its scaling
            // origin (which is the intersection of the point normals at the start and end points).

            // A good way to do this reduction is to first find the curve's extreme points, and use these as initial splitting points.
            // After this initial split, we can check each individual segment to see if it's "safe enough" based on where the
            // center of the curve is.If the on-curve point for t = 0.5 is too far off from the center, we simply split the
            // segment down the middle. Generally this is more than enough to end up with safe segments.

            Vector3          _p0 = points[0];
            Vector3          _p1, _p2, _p3;
            List <Vector3[]> _newPointsSpline = new List <Vector3[]>();

            for (int i = 3; i < PointCount; i += 3)
            {
                _p1 = points[i - 2];
                _p2 = points[i - 1];
                _p3 = points[i];

                // roots of our cubic bezier curve to find extremes
                SortedSet <float> _solutions = new SortedSet <float>();
                {
                    float?_sol1, _sol2;

                    BezierMath.CubicGetRoots(_p0.x, _p1.x, _p2.x, _p3.x, out _sol1, out _sol2);
                    if (_sol1.HasValue && _sol1.Value < 1 && _sol1.Value > 0)
                    {
                        _solutions.Add(_sol1.Value);
                    }
                    if (_sol2.HasValue && _sol2.Value < 1 && _sol2.Value > 0)
                    {
                        _solutions.Add(_sol2.Value);
                    }

                    BezierMath.CubicGetRoots(_p0.y, _p1.y, _p2.y, _p3.y, out _sol1, out _sol2);
                    if (_sol1.HasValue && _sol1.Value < 1 && _sol1.Value > 0)
                    {
                        _solutions.Add(_sol1.Value);
                    }
                    if (_sol2.HasValue && _sol2.Value < 1 && _sol2.Value > 0)
                    {
                        _solutions.Add(_sol2.Value);
                    }

                    BezierMath.CubicGetRoots(_p0.z, _p1.z, _p2.z, _p3.z, out _sol1, out _sol2);
                    if (_sol1.HasValue && _sol1.Value < 1 && _sol1.Value > 0)
                    {
                        _solutions.Add(_sol1.Value);
                    }
                    if (_sol2.HasValue && _sol2.Value < 1 && _sol2.Value > 0)
                    {
                        _solutions.Add(_sol2.Value);
                    }
                }

                // the list of new points of the offset curve
                List <Vector3[]> _newPointsCurve = new List <Vector3[]>();

                // So we're gonna need to split the starting curve at potentially more points
                // We do that by splitting in order and always taking the second split curve as the next
                // starting curve
                {
                    Vector3[] _first, _second = new Vector3[] { _p0, _p1, _p2, _p3 };
                    float     _secondSize     = 1f; // we need this to know how big the second curve is compared to the very first starting curve
                                                    // so we can split at the right point
                    foreach (float sol in _solutions)
                    {
                        BezierMath.CubicSplitCurve(_second[0], _second[1], _second[2], _second[3], _secondSize * sol, out _first, out _second);

                        _secondSize *= (1f - sol);
                        _newPointsCurve.Add(_first);
                    }
                    _newPointsCurve.Add(_second); // no more calculations with the second curve, so we can add it to the list
                }

                // check whether each bezier curve is safe or not if not split it
                {
                    int _at = _newPointsCurve.Count - 1;

                    while (_at >= 0)
                    {
                        Vector3[] _split1, _split2;
                        // where the curv t = 0.5f
                        Vector3 _zeroDotFive = BezierMath.CubicGetPoint(_newPointsCurve[_at][0], _newPointsCurve[_at][1],
                                                                        _newPointsCurve[_at][2], _newPointsCurve[_at][3], 0.5f);
                        // the center of the curve's 4 points
                        Vector3 _center = (_newPointsCurve[_at][0] + _newPointsCurve[_at][1] + _newPointsCurve[_at][2] + _newPointsCurve[_at][3]) / 4f;

                        // if they are too far away
                        if (Vector3.Distance(_zeroDotFive, _center) > safeDist)
                        {
                            // split curva at 0.5f
                            BezierMath.CubicSplitCurve(_newPointsCurve[_at][0], _newPointsCurve[_at][1], _newPointsCurve[_at][2], _newPointsCurve[_at][3], 0.5f,
                                                       out _split1, out _split2);

                            // overwrite current curve
                            _newPointsCurve[_at] = _split2;
                            // add one before it
                            _newPointsCurve.Insert(_at, _split1);
                            // we need to check the _split too again as well, so add one to at
                            _at++;
                        }
                        else
                        {
                            // no problem with this curve, move on
                            _at--;
                        }
                    }
                }

                // scale
                {
                    Vector3 _pivot;

                    for (int k = 0; k < _newPointsCurve.Count; k++)
                    {
                        // get pivot -> the intersection of the point normals at the start and end points
                        bool _doIntersect = Math3D.LineLineIntersection(
                            out _pivot,
                            _newPointsCurve[k][0],
                            (Quaternion.LookRotation(Vector3.right) * BezierMath.CubicGetFirstDerivative(_newPointsCurve[k][0], _newPointsCurve[k][1], _newPointsCurve[k][2], _newPointsCurve[k][3], 0.01f)).normalized,
                            _newPointsCurve[k][3],
                            (Quaternion.LookRotation(Vector3.right) * BezierMath.CubicGetFirstDerivative(_newPointsCurve[k][0], _newPointsCurve[k][1], _newPointsCurve[k][2], _newPointsCurve[k][3], 0.99f)).normalized
                            );

                        // scaling
                        if (!_doIntersect)   // it's essentially a line
                        // which way the right is from the line
                        {
                            Vector3 _whichWay = Vector3.Cross(_newPointsCurve[k][3] - _newPointsCurve[k][0], Vector3.up).normalized;

                            for (int j = 0; j < _newPointsCurve[k].Length; j++)
                            {
                                _newPointsCurve[k][j] -= _whichWay * amount;
                            }
                        }
                        else
                        {
                            // cache this
                            Vector3 _middleDerivative = BezierMath.CubicGetFirstDerivative(
                                _newPointsCurve[k][0],
                                _newPointsCurve[k][1],
                                _newPointsCurve[k][2],
                                _newPointsCurve[k][3], 0.5f);

                            // which way is the middle point's right
                            Vector3 _curveMiddleRight = (Quaternion.LookRotation(Vector3.right) * _middleDerivative).normalized;
                            // which way is the middle point's left
                            Vector3 _curveMiddleLeft = (Quaternion.LookRotation(Vector3.left) * _middleDerivative).normalized;

                            for (int j = 0; j < _newPointsCurve[k].Length; j++)
                            {
                                Vector3 _scaleDir = (_pivot - _newPointsCurve[k][j]).normalized;

                                // pivot is to the right
                                bool _isPivotToRight = Vector3.Angle(_scaleDir, _curveMiddleRight) <
                                                       Vector3.Angle(_scaleDir, _curveMiddleLeft);

                                // move to position based on pivot direction
                                if (_isPivotToRight)
                                {
                                    _newPointsCurve[k][j] += _scaleDir * amount;
                                }
                                else
                                {
                                    _newPointsCurve[k][j] -= _scaleDir * amount;
                                }
                            }
                        }
                    }
                }

                _newPointsSpline.AddRange(_newPointsCurve);

                _p0 = _p3;
            }

            _shiftedSpline.points    = new Vector3[_newPointsSpline.Count * 3 + 1];
            _shiftedSpline.points[0] = _newPointsSpline[0][0];

            _shiftedSpline.modes    = new BezierControlPointMode[_newPointsSpline.Count + 1];
            _shiftedSpline.modes[0] = BezierControlPointMode.Free;

            for (int i = 0; i < _newPointsSpline.Count; i++)
            {
                _shiftedSpline.modes[i + 1] = BezierControlPointMode.Free;

                for (int k = 1; k <= 3; k++)
                {
                    _shiftedSpline.points[i * 3 + k] = _newPointsSpline[i][k];
                }
            }

            return(_shiftedSpline);
        }
コード例 #14
0
ファイル: PipeLine.cs プロジェクト: alexbasic/SimpleRender
        public void Render(Scene scene)
        {
            //TransformedVector = TranslationMatrix * RotationMatrix * ScaleMatrix * OriginalVector;
            //MVPmatrix = projection * view * model;

            double[] zBuffer = new double[_screenWidth * _screenHeight];

            var rnd       = new Random();
            var cvvMatrix = Math3D.GetPerspectiveMatrix(100, _halfScreenWidth / _halfscreenHeight, 0.3d, 1000d);

            foreach (var primitive in scene.Objects)
            {
                var rotationMatrix = Math3D.GetRotationMatrix(
                    primitive.Rotation.X,
                    primitive.Rotation.Y,
                    primitive.Rotation.Z);

                var translationMatrix = Math3D.GetTranslationMatrix(primitive.Position.X, primitive.Position.Y, primitive.Position.Z);

                var scaleMatrix = Math3D.GetScaleMatrix(1, 1, 1);
                var modelMatrix = translationMatrix * (rotationMatrix * scaleMatrix);
                var viewMatrix  = Math3D.GetViewMatrix(new Vector3f(0f, 1.2f, -2f), new Vector3f(0, 0f, 0f));

                var transformMatrix = cvvMatrix * viewMatrix;// * modelMatrix;

                foreach (var triangle in primitive.Faces)
                {
                    var v1 = primitive.Vertices[triangle.Vertex1];
                    var v2 = primitive.Vertices[triangle.Vertex2];
                    var v3 = primitive.Vertices[triangle.Vertex3];

                    //TODO Здесь нужен вызов фрагментного шейдера
                    //shader.Set(v1,v2,v3) shader.Compute()

                    #region Завернуть в шейдер
                    var worldCoord1 = modelMatrix * new Vector4(v1.X, v1.Y, v1.Z, 1);
                    var worldCoord2 = modelMatrix * new Vector4(v2.X, v2.Y, v2.Z, 1);
                    var worldCoord3 = modelMatrix * new Vector4(v3.X, v3.Y, v3.Z, 1);

                    var vector1 = transformMatrix * worldCoord1;
                    var vector2 = transformMatrix * worldCoord2;
                    var vector3 = transformMatrix * worldCoord3;

                    var decartvector1 = Math3D.ConvertToDecart(vector1);
                    var decartvector2 = Math3D.ConvertToDecart(vector2);
                    var decartvector3 = Math3D.ConvertToDecart(vector3);

                    Vector3f faceNormalInWorldCoord = Math3D.CalculateNormal(Math3D.ConvertToDecart(worldCoord1), Math3D.ConvertToDecart(worldCoord2), Math3D.ConvertToDecart(worldCoord3));

                    Vector3f faceNormalInProjectionCoord = SimpleRender.Math.Vector3f.CrossProductLeft((decartvector3 - decartvector1), (decartvector2 - decartvector1));
                    faceNormalInProjectionCoord = faceNormalInProjectionCoord.Normalize();
                    var    viewDirection = new Vector4(0, 0, -1, 1);
                    double intensity     = Math3D.DotProduct(faceNormalInProjectionCoord, viewDirection);

                    //TODO Подумать нужноли это в шейдере
                    if (intensity <= 0)
                    {
                        continue;
                    }

                    //ambient = Ka,
                    //diffuse = Kd * cos(N, L),
                    //specular = Ks * pow(cos(R, V), Ns),
                    //intensity = ambient + amp * (diffuse + specular).

                    //-----------------
                    //http://www.gamedev.ru/code/articles/HLSL?page=4
                    //Lighting:
                    //Lambert (ambient lighting)
                    //Diffuse (diffuse lighting model)
                    //Phong (specular lighting model), Blinn (blinn specular lighting model)
                    //Sum of this

                    //Реалистичное освещение на основе Кука-Торренса

                    //-------------

                    var ligthSource         = scene.LightSources.First();
                    var globalLightPosition = ligthSource.Position.Normalize();

                    double illuminationIntensity = Math3D.DotProduct(faceNormalInWorldCoord, globalLightPosition);
                    var    diffuseColor          = new Vector4(
                        primitive.Mategial.DiffuseColor.X * ligthSource.Color.X,
                        primitive.Mategial.DiffuseColor.Y * ligthSource.Color.Y,
                        primitive.Mategial.DiffuseColor.Z * ligthSource.Color.Z,
                        1)
                                                   * illuminationIntensity;

                    //var reflection = (Vector3f.CrossProductLeft(faceNormalInWorldCoord ,
                    //    (Vector3f.CrossProductLeft(faceNormalInWorldCoord ,globalLightPosition) * 2.0f)) -
                    //    globalLightPosition).Normalize();   // reflected light

                    var sampleColor = scene.AmbientColor + diffuseColor * ligthSource.Intensity;

                    #endregion

                    Draw3D.SimpleRasterizeTriangle(
                        ConvertToScreenCoord0(decartvector1),
                        ConvertToScreenCoord0(decartvector2),
                        ConvertToScreenCoord0(decartvector3),
                        Image,
                        Color.FromArgb((int)(255 * Restrict(sampleColor.X)), (int)(255 * Restrict(sampleColor.Y)), (int)(255 * Restrict(sampleColor.Z))),
                        zBuffer);
                }
            }
        }
コード例 #15
0
ファイル: Mesh.cs プロジェクト: optimus-code/Q2Sharp
        public override void R_DrawAliasModel(entity_t e)
        {
            if ((e.flags & Defines.RF_WEAPONMODEL) == 0)
            {
                if (R_CullAliasModel(e))
                {
                    return;
                }
            }

            if ((e.flags & Defines.RF_WEAPONMODEL) != 0)
            {
                if (r_lefthand.value == 2F)
                {
                    return;
                }
            }

            qfiles.dmdl_t paliashdr = (qfiles.dmdl_t)currentmodel.extradata;
            Int32         i;

            if ((currententity.flags & (Defines.RF_SHELL_HALF_DAM | Defines.RF_SHELL_GREEN | Defines.RF_SHELL_RED | Defines.RF_SHELL_BLUE | Defines.RF_SHELL_DOUBLE)) != 0)
            {
                Math3D.VectorClear(shadelight);
                if ((currententity.flags & Defines.RF_SHELL_HALF_DAM) != 0)
                {
                    shadelight[0] = 0.56F;
                    shadelight[1] = 0.59F;
                    shadelight[2] = 0.45F;
                }

                if ((currententity.flags & Defines.RF_SHELL_DOUBLE) != 0)
                {
                    shadelight[0] = 0.9F;
                    shadelight[1] = 0.7F;
                }

                if ((currententity.flags & Defines.RF_SHELL_RED) != 0)
                {
                    shadelight[0] = 1F;
                }
                if ((currententity.flags & Defines.RF_SHELL_GREEN) != 0)
                {
                    shadelight[1] = 1F;
                }
                if ((currententity.flags & Defines.RF_SHELL_BLUE) != 0)
                {
                    shadelight[2] = 1F;
                }
            }
            else if ((currententity.flags & Defines.RF_FULLBRIGHT) != 0)
            {
                for (i = 0; i < 3; i++)
                {
                    shadelight[i] = 1F;
                }
            }
            else
            {
                R_LightPoint(currententity.origin, shadelight);
                if ((currententity.flags & Defines.RF_WEAPONMODEL) != 0)
                {
                    if (shadelight[0] > shadelight[1])
                    {
                        if (shadelight[0] > shadelight[2])
                        {
                            r_lightlevel.value = 150 * shadelight[0];
                        }
                        else
                        {
                            r_lightlevel.value = 150 * shadelight[2];
                        }
                    }
                    else
                    {
                        if (shadelight[1] > shadelight[2])
                        {
                            r_lightlevel.value = 150 * shadelight[1];
                        }
                        else
                        {
                            r_lightlevel.value = 150 * shadelight[2];
                        }
                    }
                }

                if (gl_monolightmap.string_renamed[0] != '0')
                {
                    var s = shadelight[0];
                    if (s < shadelight[1])
                    {
                        s = shadelight[1];
                    }
                    if (s < shadelight[2])
                    {
                        s = shadelight[2];
                    }
                    shadelight[0] = s;
                    shadelight[1] = s;
                    shadelight[2] = s;
                }
            }

            if ((currententity.flags & Defines.RF_MINLIGHT) != 0)
            {
                for (i = 0; i < 3; i++)
                {
                    if (shadelight[i] > 0.1F)
                    {
                        break;
                    }
                }
                if (i == 3)
                {
                    shadelight[0] = 0.1F;
                    shadelight[1] = 0.1F;
                    shadelight[2] = 0.1F;
                }
            }

            if ((currententity.flags & Defines.RF_GLOW) != 0)
            {
                Single scale;
                Single min;
                scale = ( Single )(0.1F * Math.Sin(r_newrefdef.time * 7));
                for (i = 0; i < 3; i++)
                {
                    min            = shadelight[i] * 0.8F;
                    shadelight[i] += scale;
                    if (shadelight[i] < min)
                    {
                        shadelight[i] = min;
                    }
                }
            }

            if ((r_newrefdef.rdflags & Defines.RDF_IRGOGGLES) != 0 && (currententity.flags & Defines.RF_IR_VISIBLE) != 0)
            {
                shadelight[0] = 1F;
                shadelight[1] = 0F;
                shadelight[2] = 0F;
            }

            shadedots = r_avertexnormal_dots[(( Int32 )(currententity.angles[1] * (SHADEDOT_QUANT / 360))) & (SHADEDOT_QUANT - 1)];
            var an = ( Single )(currententity.angles[1] / 180 * Math.PI);

            shadevector[0] = ( Single )Math.Cos(-an);
            shadevector[1] = ( Single )Math.Sin(-an);
            shadevector[2] = 1;
            Math3D.VectorNormalize(shadevector);
            c_alias_polys += paliashdr.num_tris;
            if ((currententity.flags & Defines.RF_DEPTHHACK) != 0)
            {
                GL.DepthRange(gldepthmin, gldepthmin + 0.3 * (gldepthmax - gldepthmin));
            }
            if ((currententity.flags & Defines.RF_WEAPONMODEL) != 0 && (r_lefthand.value == 1F))
            {
                GL.MatrixMode(MatrixMode.Projection);
                GL.PushMatrix();
                GL.LoadIdentity();
                GL.Scale(-1, 1, 1);
                MYgluPerspective(r_newrefdef.fov_y, ( Single )r_newrefdef.width / r_newrefdef.height, 4, 4096);
                GL.MatrixMode(MatrixMode.Modelview);
                GL.CullFace(CullFaceMode.Back);
            }

            GL.PushMatrix();
            e.angles[PITCH] = -e.angles[PITCH];
            R_RotateForEntity(e);
            e.angles[PITCH] = -e.angles[PITCH];
            image_t skin;

            if (currententity.skin != null)
            {
                skin = currententity.skin;
            }
            else
            {
                if (currententity.skinnum >= qfiles.MAX_MD2SKINS)
                {
                    skin = currentmodel.skins[0];
                }
                else
                {
                    skin = currentmodel.skins[currententity.skinnum];
                    if (skin == null)
                    {
                        skin = currentmodel.skins[0];
                    }
                }
            }

            if (skin == null)
            {
                skin = r_notexture;
            }
            GL_Bind(skin.texnum);
            GL.ShadeModel(ShadingModel.Smooth);
            GL_TexEnv(( Int32 )All.Modulate);
            if ((currententity.flags & Defines.RF_TRANSLUCENT) != 0)
            {
                GL.Enable(EnableCap.Blend);
            }

            if ((currententity.frame >= paliashdr.num_frames) || (currententity.frame < 0))
            {
                VID.Printf(Defines.PRINT_ALL, "R_DrawAliasModel " + currentmodel.name + ": no such frame " + currententity.frame + '\\');
                currententity.frame    = 0;
                currententity.oldframe = 0;
            }

            if ((currententity.oldframe >= paliashdr.num_frames) || (currententity.oldframe < 0))
            {
                VID.Printf(Defines.PRINT_ALL, "R_DrawAliasModel " + currentmodel.name + ": no such oldframe " + currententity.oldframe + '\\');
                currententity.frame    = 0;
                currententity.oldframe = 0;
            }

            if (r_lerpmodels.value == 0F)
            {
                currententity.backlerp = 0;
            }
            GL_DrawAliasFrameLerp(paliashdr, currententity.backlerp);
            GL_TexEnv(( Int32 )All.Replace);
            GL.ShadeModel(ShadingModel.Flat);
            GL.PopMatrix();
            if ((currententity.flags & Defines.RF_WEAPONMODEL) != 0 && (r_lefthand.value == 1F))
            {
                GL.MatrixMode(MatrixMode.Projection);
                GL.PopMatrix();
                GL.MatrixMode(MatrixMode.Modelview);
                GL.CullFace(CullFaceMode.Front);
            }

            if ((currententity.flags & Defines.RF_TRANSLUCENT) != 0)
            {
                GL.Disable(EnableCap.Blend);
            }

            if ((currententity.flags & Defines.RF_DEPTHHACK) != 0)
            {
                GL.DepthRange(gldepthmin, gldepthmax);
            }
            if (gl_shadows.value != 0F && (currententity.flags & (Defines.RF_TRANSLUCENT | Defines.RF_WEAPONMODEL)) == 0)
            {
                GL.PushMatrix();
                R_RotateForEntity(e);
                GL.Disable(EnableCap.Texture2D);
                GL.Enable(EnableCap.Blend);
                GL.Color4(0, 0, 0, 0.5F);
                GL_DrawAliasShadow(paliashdr, currententity.frame);
                GL.Enable(EnableCap.Texture2D);
                GL.Disable(EnableCap.Blend);
                GL.PopMatrix();
            }

            GL.Color4(1, 1, 1, 1);
        }
コード例 #16
0
        public void Select(Transform transform, Vector2 mousePos, Camera camera, out int selVertex, out int selFace, out UnorderedPair <int> selEdge, float radius = 10, float bump = 0.2f)
        {
            selVertex = -1;
            selFace   = -1;
            selEdge   = new UnorderedPair <int>(-1, -1);

            float minDist = Mathf.Infinity;

            Ray ray = camera.ScreenPointToRay(mousePos);

            ray.origin    = transform.InverseTransformPoint(ray.origin);
            ray.direction = transform.InverseTransformDirection(ray.direction);

            for (int v = 0; v < vertices.Count; v++)
            {
                Vertex vert = vertices[v];

                Vector3 world  = transform.TransformPoint(vert.position);
                Vector3 screen = camera.WorldToScreenPoint(world);
                if (screen.z > 0)
                {
                    screen.z = 0;
                    float mouseDist2 = Vector2.SqrMagnitude((Vector2)screen - mousePos);

                    float camDist = Vector3.Distance(camera.transform.position, world) - bump * 3;
                    if (mouseDist2 < radius * radius && camDist < minDist)
                    {
                        selVertex = v;
                        minDist   = camDist;
                    }
                }
            }

            foreach (var e in GetEdges())
            {
                Vertex vert1 = vertices[e.t1];
                Vertex vert2 = vertices[e.t2];

                Vector3 v1      = vert1.position;
                Vector3 v2      = vert2.position;
                Vector3 segment = v2 - v1;

                Vector3 c     = Vector3.Cross(camera.transform.forward, segment);
                Vector3 n     = Vector3.Cross(c, segment);
                Plane   plane = new Plane(n, v1);
                float   camDist;

                if (plane.Raycast(ray, out camDist) && camDist - bump < minDist)
                {
                    Vector3 hitPos  = ray.GetPoint(camDist);
                    Vector3 hitProj = Math3D.ProjectPointOnLineSegment(v1, v2, hitPos);

                    Vector3 projScreen = camera.WorldToScreenPoint(transform.TransformPoint(hitProj));
                    if (projScreen.z > 0 && Vector2.Distance(projScreen, mousePos) < radius * 0.6f)
                    {
                        selEdge   = e;
                        selVertex = -1;
                        minDist   = camDist - bump;
                    }
                }
            }

            for (int f = 0; f < faces.Count; f++)
            {
                Face    face   = faces[f];
                Vector3 normal = face.GetNormal(this);
                Plane   plane  = new Plane(normal, vertices[face.vertices[0]].position);

                float dist;
                if (plane.Raycast(ray, out dist) && dist < minDist)
                {
                    Vector3 hitPos = ray.GetPoint(dist);

                    bool inside = true;

                    for (int i = 0; i < face.vertices.Count; i++)
                    {
                        int j = (i + 1) % face.vertices.Count;

                        Vector3 v1 = vertices[face.vertices[i]].position;
                        Vector3 v2 = vertices[face.vertices[j]].position;

                        Vector3 edge  = v2 - v1;
                        Vector3 toHit = hitPos - v1;
                        Vector3 cross = Vector3.Cross(edge, toHit);

                        if (Vector3.Dot(cross, normal) < 0)
                        {
                            inside = false;
                            break;
                        }
                    }

                    if (inside)
                    {
                        selVertex  = -1;
                        selEdge.t1 = -1;
                        selEdge.t2 = -1;
                        selFace    = f;
                        minDist    = dist;
                    }
                }
            }
        }
コード例 #17
0
ファイル: Mesh.cs プロジェクト: optimus-code/Q2Sharp
        public virtual void GL_DrawAliasFrameLerp(qfiles.dmdl_t paliashdr, Single backlerp)
        {
            qfiles.daliasframe_t frame = paliashdr.aliasFrames[currententity.frame];
            Int32[] verts = frame.verts;
            qfiles.daliasframe_t oldframe = paliashdr.aliasFrames[currententity.oldframe];
            Int32[] ov = oldframe.verts;
            Single  alpha;
            Int32   size;

            if ((currententity.flags & Defines.RF_TRANSLUCENT) != 0)
            {
                alpha = currententity.alpha;
            }
            else
            {
                alpha = 1F;
            }
            if ((currententity.flags & (Defines.RF_SHELL_RED | Defines.RF_SHELL_GREEN | Defines.RF_SHELL_BLUE | Defines.RF_SHELL_DOUBLE | Defines.RF_SHELL_HALF_DAM)) != 0)
            {
                GL.Disable(EnableCap.Texture2D);
            }
            var frontlerp = 1F - backlerp;

            Math3D.VectorSubtract(currententity.oldorigin, currententity.origin, frontv);
            Math3D.AngleVectors(currententity.angles, vectors[0], vectors[1], vectors[2]);
            move[0] = Math3D.DotProduct(frontv, vectors[0]);
            move[1] = -Math3D.DotProduct(frontv, vectors[1]);
            move[2] = Math3D.DotProduct(frontv, vectors[2]);
            Math3D.VectorAdd(move, oldframe.translate, move);
            for (var i = 0; i < 3; i++)
            {
                move[i]   = backlerp * move[i] + frontlerp * frame.translate[i];
                frontv[i] = frontlerp * frame.scale[i];
                backv[i]  = backlerp * oldframe.scale[i];
            }

            GL_LerpVerts(paliashdr.num_xyz, ov, verts, move, frontv, backv);
            new Pinnable(vertexArrayBuf.Array, (ptr) =>
            {
                GL.VertexPointer(3, VertexPointerType.Float, 0, ptr);
            });
            if ((currententity.flags & (Defines.RF_SHELL_RED | Defines.RF_SHELL_GREEN | Defines.RF_SHELL_BLUE | Defines.RF_SHELL_DOUBLE | Defines.RF_SHELL_HALF_DAM)) != 0)
            {
                GL.Color4(shadelight[0], shadelight[1], shadelight[2], alpha);
            }
            else
            {
                GL.EnableClientState(ArrayCap.ColorArray);
                new Pinnable(colorArrayBuf.Array, (ptr) =>
                {
                    GL.ColorPointer(4, ColorPointerType.Float, 0, ptr);
                });
                SingleBuffer color = colorArrayBuf;
                Single       l;
                size = paliashdr.num_xyz;
                var j = 0;
                for (var i = 0; i < size; i++)
                {
                    l = shadedots[(verts[i] >> 24) & 0xFF];
                    color.Put(j, l * shadelight[0]);
                    color.Put(j + 1, l * shadelight[1]);
                    color.Put(j + 2, l * shadelight[2]);
                    color.Put(j + 3, alpha);
                    j += 4;
                }
            }

            GL.ClientActiveTexture(TextureUnit.Texture0);
            new Pinnable(textureArrayBuf.Array, (ptr) =>
            {
                GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, ptr);
            });
            var pos = 0;

            Int32[]      counts           = paliashdr.counts;
            Int32Buffer  srcIndexBuf      = null;
            SingleBuffer dstTextureCoords = textureArrayBuf;
            SingleBuffer srcTextureCoords = paliashdr.textureCoordBuf;
            var          dstIndex         = 0;
            var          srcIndex         = 0;
            Int32        count;
            Int32        mode;

            size = counts.Length;
            for (var j = 0; j < size; j++)
            {
                count = counts[j];
                if (count == 0)
                {
                    break;
                }
                srcIndexBuf = paliashdr.indexElements[j];
                mode        = ( Int32 )PrimitiveType.TriangleStrip;
                if (count < 0)
                {
                    mode  = ( Int32 )PrimitiveType.TriangleFan;
                    count = -count;
                }

                srcIndex = pos << 1;
                srcIndex--;
                for (var k = 0; k < count; k++)
                {
                    dstIndex = srcIndexBuf.Get(k) << 1;
                    dstTextureCoords.Put(dstIndex, srcTextureCoords.Get(++srcIndex));
                    dstTextureCoords.Put(++dstIndex, srcTextureCoords.Get(++srcIndex));
                }
                new Pinnable(srcIndexBuf.Array, (ptr) =>
                {
                    GL.DrawElements(( PrimitiveType )mode, 1, DrawElementsType.UnsignedInt, ptr);
                });
                pos += count;
            }

            if ((currententity.flags & (Defines.RF_SHELL_RED | Defines.RF_SHELL_GREEN | Defines.RF_SHELL_BLUE | Defines.RF_SHELL_DOUBLE | Defines.RF_SHELL_HALF_DAM)) != 0)
            {
                GL.Enable(EnableCap.Texture2D);
            }
            GL.DisableClientState(ArrayCap.ColorArray);
        }
コード例 #18
0
        // ======================================================================
        // Handle mouse events.
        // ----------------------------------------------------------------------
        void ProcessMouseEvents(Rect titleArea, Rect dataArea)
        {
            Vector2 mousePosition = Event.current.mousePosition;

            switch (Event.current.type)
            {
            case EventType.ScrollWheel: {
                if (dataArea.Contains(mousePosition))
                {
                    Vector2 delta = 8f * Event.current.delta;
                    if (Math3D.IsZero(myVScrollbarSize))
                    {
                        delta.y = 0;
                    }
                    if (Math3D.IsZero(myHScrollbarSize))
                    {
                        delta.x = 0;
                    }
                    myScrollbarPosition += delta;
                    if (myScrollbarPosition.x < 0)
                    {
                        myScrollbarPosition.x = 0;
                    }
                    if (myScrollbarPosition.y < 0)
                    {
                        myScrollbarPosition.y = 0;
                    }
                    if (myScrollbarPosition.x > myColumnDataSize.x - myHScrollbarSize)
                    {
                        myScrollbarPosition.x = myColumnDataSize.x - myHScrollbarSize;
                    }
                    if (myScrollbarPosition.y > myColumnDataSize.y - myVScrollbarSize)
                    {
                        myScrollbarPosition.y = myColumnDataSize.y - myVScrollbarSize;
                    }
                    Event.current.Use();
                }
                break;
            }

            case EventType.MouseDown: {
                if (dataArea.Contains(mousePosition) || titleArea.Contains(mousePosition))
                {
                    // Determine selected column.
                    float         x = mousePosition.x - titleArea.x + myScrollbarPosition.x;
                    DSTableColumn selectedColumn = null;
                    foreach (var c in myColumns)
                    {
                        selectedColumn = c;
                        float columnWidth = selectedColumn.DataSize.x;
                        if (x < columnWidth)
                        {
                            break;
                        }
                        x -= columnWidth;
                    }
                    // Determine selected row.
                    int selectedRow = -1;
                    if (dataArea.Contains(mousePosition))
                    {
                        float y = mousePosition.y - dataArea.y + myScrollbarPosition.y - 6f;
                        for (int row = 0; row < myRowHeights.Length; ++row)
                        {
                            float rowHeight = myRowHeights[row];
                            if (y < rowHeight)
                            {
                                selectedRow = row;
                                break;
                            }
                            y -= rowHeight;
                        }
                    }
                    if (selectedColumn != mySelectedColumn || selectedRow != mySelectedRow)
                    {
                        mySelectedColumn = selectedColumn;
                        mySelectedRow    = selectedRow;
                        myDataSource.OnMouseDown(this, selectedColumn, selectedRow);
                    }
                    Event.current.Use();
                }
                break;
            }

            case EventType.MouseUp: {
                break;
            }
            }
        }
コード例 #19
0
            public override bool Think(edict_t self)
            {
                float[] spot1 = new float[] { 0, 0, 0 }, spot2 = new float[] { 0, 0, 0 };
                float[] temp  = new float[] { 0, 0, 0 };
                float   chance;
                trace_t tr;
                int     enemy_range;
                float   enemy_yaw;

                if (self.enemy.health > 0)
                {
                    Math3D.VectorCopy(self.s.origin, spot1);
                    spot1[2] += self.viewheight;
                    Math3D.VectorCopy(self.enemy.s.origin, spot2);
                    spot2[2] += self.enemy.viewheight;
                    tr        = GameBase.gi.Trace(spot1, null, null, spot2, self, Defines.CONTENTS_SOLID | Defines.CONTENTS_MONSTER | Defines.CONTENTS_SLIME | Defines.CONTENTS_LAVA);
                    if (tr.ent != self.enemy)
                    {
                        return(false);
                    }
                }

                enemy_range = GameUtil.Range(self, self.enemy);
                Math3D.VectorSubtract(self.enemy.s.origin, self.s.origin, temp);
                enemy_yaw      = Math3D.Vectoyaw(temp);
                self.ideal_yaw = enemy_yaw;
                if (enemy_range == Defines.RANGE_MELEE)
                {
                    if (self.monsterinfo.melee != null)
                    {
                        self.monsterinfo.attack_state = Defines.AS_MELEE;
                    }
                    else
                    {
                        self.monsterinfo.attack_state = Defines.AS_MISSILE;
                    }
                    return(true);
                }

                if (self.monsterinfo.attack == null)
                {
                    return(false);
                }
                if (GameBase.level.time < self.monsterinfo.attack_finished)
                {
                    return(false);
                }
                if (enemy_range == Defines.RANGE_FAR)
                {
                    return(false);
                }
                if ((self.monsterinfo.aiflags & Defines.AI_STAND_GROUND) != 0)
                {
                    chance = 0.4F;
                }
                else if (enemy_range == Defines.RANGE_MELEE)
                {
                    chance = 0.8F;
                }
                else if (enemy_range == Defines.RANGE_NEAR)
                {
                    chance = 0.8F;
                }
                else if (enemy_range == Defines.RANGE_MID)
                {
                    chance = 0.8F;
                }
                else
                {
                    return(false);
                }

                if (Lib.Random() < chance)
                {
                    self.monsterinfo.attack_state    = Defines.AS_MISSILE;
                    self.monsterinfo.attack_finished = GameBase.level.time + 2 * Lib.Random();
                    return(true);
                }

                if ((self.flags & Defines.FL_FLY) != 0)
                {
                    if (Lib.Random() < 0.3)
                    {
                        self.monsterinfo.attack_state = Defines.AS_SLIDING;
                    }
                    else
                    {
                        self.monsterinfo.attack_state = Defines.AS_STRAIGHT;
                    }
                }

                return(false);
            }
コード例 #20
0
        private static Tuple <Point3D, Vector3D>[] GetFilteredNearby(Point3D[] nearby, Point3D position, Vector3D dragVelocity, ITriangle dragPlane, double minDot_LeftRight, double minDot_UpDown)
        {
            List <Tuple <Point3D, Vector3D> > retVal = new List <Tuple <Point3D, Vector3D> >();

            // Get the portion of the drag velocity that is along the plane, then convert to a unit vector
            Vector3D?velocity = GetVectorAlongPlaneUnit(dragVelocity, dragPlane);

            if (velocity == null)
            {
                return(retVal.ToArray());
            }

            for (int cntr = 0; cntr < nearby.Length; cntr++)
            {
                Vector3D directionToPoint = nearby[cntr] - position;

                DoubleVector directionSplit = Math3D.SplitVector(directionToPoint, dragPlane);

                #region Left/Right

                if (Math3D.IsNearZero(directionSplit.Standard))
                {
                    continue;
                }

                Vector3D directionAlongPlaneUnit = directionSplit.Standard.ToUnit();

                // Compare left/right (it's more restrictive)
                double dotLeftRight = Vector3D.DotProduct(directionAlongPlaneUnit, velocity.Value);
                if (dotLeftRight < minDot_LeftRight)
                {
                    continue;
                }

                #endregion
                #region Up/Down

                // Get the portion along the velocity, then add the portion away from the plane (which eliminates the left/right part)
                Vector3D directionUpDownUnit = directionToPoint.GetProjectedVector(velocity.Value) + directionSplit.Orth;
                if (Math3D.IsNearZero(directionUpDownUnit))
                {
                    continue;
                }

                directionUpDownUnit.Normalize();

                // Compare up/down
                double dotUpDown = Vector3D.DotProduct(directionUpDownUnit, velocity.Value);
                if (dotUpDown < minDot_UpDown)
                {
                    continue;
                }

                #endregion

                // Add it (only storing the up/down portion, because that's all that's needed)
                retVal.Add(Tuple.Create(nearby[cntr], directionUpDownUnit));
            }

            return(retVal.ToArray());
        }
コード例 #21
0
ファイル: Form1.cs プロジェクト: Mexahoid/CSF
 public Cube(int Width, int Height, int Depth, Math3D.Point3D origin)
 {
     width = Width;
     height = Height;
     depth = Depth;
     cubeOrigin = origin;
 }
コード例 #22
0
        private void ChooseForcePoints()
        {
            SortedList <int, List <Point3D>[]> pointSets = new SortedList <int, List <Point3D>[]>();

            for (int cntr = 0; cntr < _numSets; cntr++)
            {
                //TODO:  This method should return barycentric coords directly
                // Create random points across the triangles
                SortedList <int, List <Point3D> > points = Math3D.GetRandomPoints_OnHull_Structured(_triangles, _numPointsPerSet);

                // Add these to the sets
                foreach (int triangleIndex in points.Keys)
                {
                    if (!pointSets.ContainsKey(triangleIndex))
                    {
                        pointSets.Add(triangleIndex, new List <Point3D> [_numSets]);
                    }

                    pointSets[triangleIndex][cntr] = points[triangleIndex];
                }
            }

            foreach (int triangleIndex in pointSets.Keys)
            {
                List <Vector[]> localSets = new List <Vector[]>();

                for (int setCntr = 0; setCntr < _numSets; setCntr++)
                {
                    List <Point3D> points = pointSets[triangleIndex][setCntr];

                    if (points == null || points.Count == 0)
                    {
                        localSets.Add(null);
                        continue;
                    }

                    Vector[] set = new Vector[points.Count];
                    localSets.Add(set);

                    for (int cntr = 0; cntr < points.Count; cntr++)
                    {
                        set[cntr] = Math3D.ToBarycentric(this.Triangles[triangleIndex], points[cntr]);
                    }
                }

                // Store these sets in this triangle
                this.Triangles[triangleIndex].StoreForcePointSets(localSets);
            }

            // Calculate the sample radius
            if (_triangles.Length > 0)
            {
                // The sum of the volumes of point samples needs to equal the volume of the hull:
                // N(4/3 pi r^3)=Vol
                // r=cube root((Vol/N)/(4/3 pi))

                var aabb = Math3D.GetAABB(_triangles[0].AllPoints);     // using AABB as a safe way to get the volume of the hull

                double volume = Math.Abs(aabb.Item2.X - aabb.Item1.X) * Math.Abs(aabb.Item2.Y - aabb.Item1.Y) * Math.Abs(aabb.Item2.Z - aabb.Item1.Z);

                double intermediate = (volume / _numPointsPerSet) / ((4d / 3d) * Math.PI);

                _sampleRadius = Math.Abs(Math.Pow(intermediate, 1d / 3d));
            }
            else
            {
                _sampleRadius = 0d;
            }
        }