Exemplo n.º 1
0
        public Camera(Math.Matrix projection)
        {
            _orientation = new Gk3Main.Math.Quaternion();
            _position    = new Gk3Main.Math.Vector3();

            _projection = projection;
        }
Exemplo n.º 2
0
 public Layer(uint size, Layer prevLayer = null)
 {
     Size        = size;
     NeuronValue = new Math.Matrix <double>(size, 1);
     Bias        = new Math.Matrix <double>(size, 1);
     PrevLayer   = prevLayer;
 }
Exemplo n.º 3
0
        public static void LerpToMatrix(float amount,
                                        ref FrameTransformation t1, ref FrameTransformation t2,
                                        out Math.Matrix result)
        {
            float invAmount = 1.0f - amount;

            result = t1._original;

            // TODO: right now we're doing a naive interpolation,
            // which will work, but doesn't look as good as breaking
            // apart the matrix into components (rotation, scale, translation)
            // and interpolating the individual components with lerp/slerp
            result.M11 = t1._original.M11 * invAmount + t2._original.M11 * amount;
            result.M12 = t1._original.M12 * invAmount + t2._original.M12 * amount;
            result.M13 = t1._original.M13 * invAmount + t2._original.M13 * amount;
            result.M14 = t1._original.M14 * invAmount + t2._original.M14 * amount;

            result.M21 = t1._original.M21 * invAmount + t2._original.M21 * amount;
            result.M22 = t1._original.M22 * invAmount + t2._original.M22 * amount;
            result.M23 = t1._original.M23 * invAmount + t2._original.M23 * amount;
            result.M24 = t1._original.M24 * invAmount + t2._original.M24 * amount;

            result.M31 = t1._original.M31 * invAmount + t2._original.M31 * amount;
            result.M32 = t1._original.M32 * invAmount + t2._original.M32 * amount;
            result.M33 = t1._original.M33 * invAmount + t2._original.M33 * amount;
            result.M34 = t1._original.M34 * invAmount + t2._original.M34 * amount;

            result.M41 = t1._translation.X * invAmount + t2._translation.X * amount;
            result.M42 = t1._translation.Y * invAmount + t2._translation.Y * amount;
            result.M43 = t1._translation.Z * invAmount + t2._translation.Z * amount;
        }
Exemplo n.º 4
0
        /// <summary>
        /// "Batched" version of RenderAt(). This version is much faster, but
        /// it must be called between BeginBatchRender() and EndBatchRender().
        /// </summary>
        public void RenderAtBatch(Math.Vector3 position, float angle, Camera camera)
        {
            if (!_loaded)
            {
                return;
            }

            Math.Matrix world = Math.Matrix.RotateY(angle)
                                * Math.Matrix.Translate(position);

            foreach (ModMesh mesh in _meshes)
            {
                Math.Matrix worldview;

                if (mesh.AnimatedTransformMatrix.HasValue)
                {
                    if (mesh.AnimatedTransformIsAbsolute)
                    {
                        worldview = mesh.AnimatedTransformMatrix.Value * TempTransform * camera.ViewProjection;
                    }
                    else
                    {
                        worldview = mesh.AnimatedTransformMatrix.Value * world * camera.ViewProjection;
                    }
                }
                else
                {
                    worldview = mesh.TransformMatrix * world * camera.ViewProjection;
                }

                _effect.SetParameter("ModelViewProjection", worldview);

                foreach (ModMeshSection section in mesh.sections)
                {
                    _effect.SetParameter("Diffuse", section.textureResource, 0);
                    _effect.CommitParams();

                    VertexBuffer vertices;
                    if (section.AnimatedVertices != null)
                    {
                        section.AnimatedVertexBuffer.SetData(section.AnimatedVertices, 0, (int)section.numVerts * _elements.Stride / 4);
                        vertices = section.AnimatedVertexBuffer;
                    }
                    else
                    {
                        vertices = section.vertexBuffer;
                    }

                    RendererManager.CurrentRenderer.SetVertexBuffer(vertices);
                    RendererManager.CurrentRenderer.Indices = section.indexBuffer;
                    RendererManager.CurrentRenderer.DrawIndexed(PrimitiveType.Triangles, 0, 0, vertices.NumVertices, 0, section.indices.Length);
                }
            }
        }
Exemplo n.º 5
0
        public Frustum(Math.Matrix modelViewProjection)
        {
            // need this to make the compiler happy
            _near   = new Math.Vector4();
            _far    = new Math.Vector4();
            _right  = new Math.Vector4();
            _left   = new Math.Vector4();
            _bottom = new Math.Vector4();
            _top    = new Math.Vector4();

            Build(modelViewProjection);
        }
Exemplo n.º 6
0
        public AxisAlignedBoundingBox Transform(Math.Matrix transform)
        {
            Math.Vector3 transformedBBMin = transform * Min;
            Math.Vector3 transformedBBMax = transform * Max;

            AxisAlignedBoundingBox newBBox = new AxisAlignedBoundingBox();

            newBBox.Min.X = System.Math.Min(transformedBBMin.X, transformedBBMax.X);
            newBBox.Min.Y = System.Math.Min(transformedBBMin.Y, transformedBBMax.Y);
            newBBox.Min.Z = System.Math.Min(transformedBBMin.Z, transformedBBMax.Z);
            newBBox.Max.X = System.Math.Max(transformedBBMin.X, transformedBBMax.X);
            newBBox.Max.Y = System.Math.Max(transformedBBMin.Y, transformedBBMax.Y);
            newBBox.Max.Z = System.Math.Max(transformedBBMin.Z, transformedBBMax.Z);

            return(newBBox);
        }
Exemplo n.º 7
0
        public void Train(double[] inputs, double[] answersArray)
        {
            var output = Predict(inputs);

            var answers = new Math.Matrix <double>();

            answers = answers.FromArray(answersArray);

            //Error
            var error = answers - output;

            //hidden error

            var gradient = Matrix <double> .Map(output, Dsigmoid);

            gradient.HadamardProduct(error);
            gradient *= LearningRate;

            var hidden_wt_delta = Matrix <double> .Multiply(gradient, Matrix <double> .Transpose(Layers[Layers.Count - 2].NeuronValue));


            Layers[Layers.Count - 2].Weights += hidden_wt_delta;
            Layers[Layers.Count - 1].Bias    += gradient;

            //Layers[Layers.Count-2].Weights.Print();

            var prevError = error;

            for (int i = Layers.Count - 2; i > 0; i--)
            {
                var hidden_error = Matrix <double> .Multiply(Matrix <double> .Transpose(Layers[i].Weights), prevError);

                prevError = hidden_error;
                gradient  = Matrix <double> .Map(Layers[i].NeuronValue, Dsigmoid);

                gradient.HadamardProduct(hidden_error);
                gradient *= LearningRate;

                hidden_wt_delta = Matrix <double> .Multiply(gradient, Matrix <double> .Transpose(Layers[i - 1].NeuronValue));

                Layers[i - 1].Weights += hidden_wt_delta;
                Layers[i].Bias        += gradient;
            }
        }
Exemplo n.º 8
0
        public void Render(Camera camera, Math.Matrix world)
        {
            if (_vertices == null)
            {
                createVertices();
            }

            Math.Matrix modelViewProjection = world * camera.ViewProjection;

            _effect.Bind();
            _effect.SetParameter("ModelViewProjection", modelViewProjection);
            _effect.Begin();

            //RendererManager.CurrentRenderer.RenderIndices(PrimitiveType.Lines, 0, 8, _indices, _vertices, _declaration);
            //RendererManager.CurrentRenderer.RenderPrimitives(PrimitiveType.Lines, 0, 8, _vertices);
            //RendererManager.CurrentRenderer.RenderPrimitives(PrimitiveType.Lines, 8, 8, _vertices);

            _effect.End();
        }
Exemplo n.º 9
0
        public Math.Vector3 Unproject(Math.Vector3 source,
                                      ref Math.Matrix projection, ref Math.Matrix view, ref Math.Matrix world)
        {
            Math.Vector4 result;
            result.X = ((source.X - X) * 2 / Width) - 1;
            result.Y = 1 - ((source.Y - Y) * 2 / Height);
            result.Z = source.Z;
            result.W = 1.0f;

            Math.Matrix invProj, invView, invWorld;
            Math.Matrix.Invert(ref projection, out invProj);
            Math.Matrix.Invert(ref view, out invView);
            Math.Matrix.Invert(ref world, out invWorld);

            result = invProj * result;
            result = invView * result;
            result = invWorld * result;
            result = result / result.W;

            return(new Math.Vector3(result.X, result.Y, result.Z));
        }
Exemplo n.º 10
0
        public void Render(Camera camera)
        {
            if (SceneManager.CurrentFilterMode == TextureFilterMode.None)
            {
                RendererManager.CurrentRenderer.SamplerStates[0] = SamplerState.PointClamp;
                RendererManager.CurrentRenderer.SamplerStates[1] = SamplerState.PointClamp;
            }
            else
            {
                RendererManager.CurrentRenderer.SamplerStates[0] = SamplerState.LinearClamp;
                RendererManager.CurrentRenderer.SamplerStates[1] = SamplerState.LinearClamp;
            }

            RendererManager.CurrentRenderer.DepthTestEnabled = false;
            RendererManager.CurrentRenderer.SetVertexBuffer(_vertices);
            RendererManager.CurrentRenderer.Indices = _indices;

            _skyboxEffect.Bind();

            _skyboxEffect.SetParameter("Diffuse", _cubeMap, 0);

            Math.Matrix modelViewProjection = Math.Matrix.RotateY(_azimuth) * Math.Matrix.Translate(camera.Position.X, camera.Position.Y, camera.Position.Z) * camera.View * camera.Projection;
            _skyboxEffect.SetParameter("ModelViewProjection", modelViewProjection);


            _skyboxEffect.Begin();

            Graphics.RendererManager.CurrentRenderer.DrawIndexed(PrimitiveType.Triangles, 0, 0, _vertices.NumVertices, 0, _indices.Length);

            _skyboxEffect.End();

            if (_sun != null)
            {
                BillboardManager.AddBillboard(camera.Position + -_sunDirection * 500.0f, 100.0f, 100.0f, _sun, _sunMask);
                BillboardManager.RenderBillboardsWithAlpha(camera);
            }

            RendererManager.CurrentRenderer.DepthTestEnabled = true;
        }
Exemplo n.º 11
0
 public void CreateBillboardMatrix(Math.Vector3 position, bool includePosition, out Math.Matrix matrix)
 {
     matrix = Math.Matrix.Translate(-position) *
              Math.Matrix.RotateY(CalcYaw()) *
              Math.Matrix.Translate(position);
 }
Exemplo n.º 12
0
 public Math.Vector3 Unproject(Math.Vector3 v)
 {
     Math.Matrix world = Math.Matrix.Identity;
     return(RendererManager.CurrentRenderer.Viewport.Unproject(v, ref _projection, ref _modelView, ref world));
 }
Exemplo n.º 13
0
        /// <summary>
        /// "Batched" version of Render(). This version is much faster, but
        /// it must be called between BeginBatchRender() and EndBatchRender().
        /// </summary>
        public void RenderBatch(Camera camera, Math.Matrix?transform)
        {
            if (!_isBillboard)
            {
                Math.Matrix worldViewProjection = (transform.HasValue ? transform.Value * camera.ViewProjection : camera.ViewProjection);
                //Math.Matrix worldViewProjection = camera.ViewProjection;

                foreach (ModMesh mesh in _meshes)
                {
                    Math.Matrix worldview;
                    if (mesh.AnimatedTransformMatrix.HasValue)
                    {
                        worldview = mesh.AnimatedTransformMatrix.Value * worldViewProjection;
                    }
                    else
                    {
                        worldview = mesh.TransformMatrix * worldViewProjection;
                    }


                    _effect.SetParameter("ModelViewProjection", worldview);
                    foreach (ModMeshSection section in mesh.sections)
                    {
                        _effect.SetParameter("Diffuse", section.textureResource, 0);
                        _effect.SetParameter("Color", section.color);
                        _effect.CommitParams();

                        RendererManager.CurrentRenderer.SetVertexBuffer(section.vertexBuffer);
                        RendererManager.CurrentRenderer.Indices = section.indexBuffer;
                        RendererManager.CurrentRenderer.DrawIndexed(PrimitiveType.Triangles, 0, 0, section.vertexBuffer.NumVertices, 0, section.indices.Length);
                    }
                }
            }
            else
            {
                // render the model as a billboard
                for (int i = 0; i < _meshes.Length; i++)
                {
                    Math.Vector3 meshPosition;
                    if (_useBillboardCenter)
                    {
                        meshPosition = _billboardCenter;
                    }
                    else
                    {
                        meshPosition = _meshes[i].OriginalBoundingBox.Center;
                    }

                    Math.Matrix billboardMatrix;
                    camera.CreateBillboardMatrix(meshPosition, true, out billboardMatrix);

                    _effect.SetParameter("ModelViewProjection", billboardMatrix * _meshes[i].TransformMatrix * camera.ViewProjection);
                    foreach (ModMeshSection section in _meshes[i].sections)
                    {
                        _effect.SetParameter("Diffuse", section.textureResource, 0);
                        _effect.CommitParams();

                        RendererManager.CurrentRenderer.SetVertexBuffer(section.vertexBuffer);
                        RendererManager.CurrentRenderer.Indices = section.indexBuffer;
                        RendererManager.CurrentRenderer.DrawIndexed(PrimitiveType.Triangles, 0, 0, section.vertexBuffer.NumVertices, 0, section.indices.Length);
                    }
                }
            }
        }
Exemplo n.º 14
0
 public void SetTransform(Math.Matrix transform)
 {
     AnimatedTransformMatrix = transform;
     UpdatedBoundingBox      = OriginalBoundingBox.Transform(transform);
 }
Exemplo n.º 15
0
        public void Build(Math.Matrix modelViewProjection)
        {
            _right.X = modelViewProjection.M14 - modelViewProjection.M11;
            _right.Y = modelViewProjection.M24 - modelViewProjection.M21;
            _right.Z = modelViewProjection.M34 - modelViewProjection.M31;
            _right.W = modelViewProjection.M44 - modelViewProjection.M41;
            float len = (float)System.Math.Sqrt(_right.X * _right.X + _right.Y * _right.Y + _right.Z * _right.Z);

            _right.X /= len;
            _right.Y /= len;
            _right.Z /= len;
            _right.W /= len;

            _left.X  = modelViewProjection.M14 + modelViewProjection.M11;
            _left.Y  = modelViewProjection.M24 + modelViewProjection.M21;
            _left.Z  = modelViewProjection.M34 + modelViewProjection.M31;
            _left.W  = modelViewProjection.M44 + modelViewProjection.M41;
            len      = (float)System.Math.Sqrt(_left.X * _left.X + _left.Y * _left.Y + _left.Z * _left.Z);
            _left.X /= len;
            _left.Y /= len;
            _left.Z /= len;
            _left.W /= len;

            _bottom.X  = modelViewProjection.M14 + modelViewProjection.M12;
            _bottom.Y  = modelViewProjection.M24 + modelViewProjection.M22;
            _bottom.Z  = modelViewProjection.M34 + modelViewProjection.M32;
            _bottom.W  = modelViewProjection.M44 + modelViewProjection.M42;
            len        = (float)System.Math.Sqrt(_bottom.X * _bottom.X + _bottom.Y * _bottom.Y + _bottom.Z * _bottom.Z);
            _bottom.X /= len;
            _bottom.Y /= len;
            _bottom.Z /= len;
            _bottom.W /= len;

            _top.X  = modelViewProjection.M14 - modelViewProjection.M12;
            _top.Y  = modelViewProjection.M24 - modelViewProjection.M22;
            _top.Z  = modelViewProjection.M34 - modelViewProjection.M32;
            _top.W  = modelViewProjection.M44 - modelViewProjection.M42;
            len     = (float)System.Math.Sqrt(_top.X * _top.X + _top.Y * _top.Y + _top.Z * _top.Z);
            _top.X /= len;
            _top.Y /= len;
            _top.Z /= len;
            _top.W /= len;


            _near.X  = modelViewProjection.M13;
            _near.Y  = modelViewProjection.M23;
            _near.Z  = modelViewProjection.M33;
            _near.W  = modelViewProjection.M43;
            len      = (float)System.Math.Sqrt(_near.X * _near.X + _near.Y * _near.Y + _near.Z * _near.Z);
            _near.X /= len;
            _near.Y /= len;
            _near.Z /= len;
            _near.W /= len;

            _far.X  = modelViewProjection.M14 - modelViewProjection.M13;
            _far.Y  = modelViewProjection.M24 - modelViewProjection.M23;
            _far.Z  = modelViewProjection.M34 - modelViewProjection.M33;
            _far.W  = modelViewProjection.M44 - modelViewProjection.M43;
            len     = (float)System.Math.Sqrt(_far.X * _far.X + _far.Y * _far.Y + _far.Z * _far.Z);
            _far.X /= len;
            _far.Y /= len;
            _far.Z /= len;
            _far.W /= len;
        }
Exemplo n.º 16
0
        private void play(int timeSinceStart, int duration)
        {
            int startIndex, count;

            // play model visibility
            if (_modelVisibilitySection != null)
            {
                GetAllFramesSince(_modelVisibilitySection, timeSinceStart, duration, MillisecondsPerFrame,
                                  out startIndex, out count);

                for (int i = startIndex; i < startIndex + count; i++)
                {
                    string model   = _modelVisibilitySection.Lines[i].Params[0].StringValue;
                    string onoff   = _modelVisibilitySection.Lines[i].Params[1].StringValue;
                    bool   visible = onoff.Equals("on", StringComparison.OrdinalIgnoreCase);

                    SceneManager.SetSceneModelVisibility(model, visible);
                }
            }

            if (_modelTexturesSection != null)
            {
                GetAllFramesSince(_modelTexturesSection, timeSinceStart, duration, MillisecondsPerFrame,
                                  out startIndex, out count);

                for (int i = startIndex; i < startIndex + count; i++)
                {
                    string model      = _modelTexturesSection.Lines[i].Params[0].StringValue;
                    int    meshIndex  = _modelTexturesSection.Lines[i].Params[1].IntValue;
                    int    groupIndex = _modelTexturesSection.Lines[i].Params[2].IntValue;
                    string texture    = _modelTexturesSection.Lines[i].Params[3].StringValue;

                    SceneManager.SetModelTexture(model, meshIndex, groupIndex, texture);
                }
            }

            // play sounds
            if (_soundSection != null)
            {
                GetAllFramesSince(_soundSection, timeSinceStart, duration, MillisecondsPerFrame,
                                  out startIndex, out count);

                for (int i = startIndex; i < startIndex + count; i++)
                {
                    // the indices in the little sound list *should* match "i"
                    Sound.SoundManager.PlaySound2DToChannel(_sounds[i], Sound.SoundTrackChannel.SFX);
                }
            }

            // play the dialog
            if (_gk3Section != null)
            {
                GetAllFramesSince(_gk3Section, timeSinceStart, duration, MillisecondsPerFrame,
                                  out startIndex, out count);

                for (int i = startIndex; i < startIndex + count; i++)
                {
                    string command = _gk3Section.Lines[i].Params[0].StringValue;

                    if (command.Equals("DIALOGUE", StringComparison.OrdinalIgnoreCase))
                    {
                        string yak = _gk3Section.Lines[i].Params[1].StringValue;
                        DialogManager.PlayDialogue(yak, 1, yak.StartsWith("E", StringComparison.OrdinalIgnoreCase), false);
                    }
                    else if (command.Equals("LIPSYNCH", StringComparison.OrdinalIgnoreCase))
                    {
                        string param2 = _gk3Section.Lines[i].Params[1].StringValue;

                        Actor actor = SceneManager.GetActor(param2);
                        if (actor == null)
                        {
                            continue; // couldn't find this actor for some reason, so give up
                        }
                        string param3 = _gk3Section.Lines[i].Params[2].StringValue;
                        actor.SetMouth(param3);
                    }
                }
            }

            // add any new ACT files
            if (_actionSection != null)
            {
                GetAllFramesSince(_actionSection, timeSinceStart, duration, MillisecondsPerFrame,
                                  out startIndex, out count);

                for (int i = startIndex; i < startIndex + count; i++)
                {
                    string actName = _actionSection.Lines[i].Params[0].StringValue;
                    if (actName.Length > 31)
                    {
                        actName = actName.Substring(0, 31);                      // we can get FileNotFound without this
                    }
                    if (actName.EndsWith(".ACT", StringComparison.OrdinalIgnoreCase) == false)
                    {
                        actName += ".ACT";
                    }

                    MomAct act = new MomAct();
                    act.Act   = _content.Load <Graphics.ActResource>(actName);
                    act.Model = SceneManager.GetSceneModel(act.Act.ModelName);

                    // check if this is an absolute animation or contains a transformation
                    if (_actionSection.Lines[i].Params.Count > 1)
                    {
                        act.IsAbsolute = true;

                        Math.Matrix transform = Math.Matrix.Translate(-_actionSection.Lines[i].Params[1].FloatValue,
                                                                      -_actionSection.Lines[i].Params[3].FloatValue,
                                                                      -_actionSection.Lines[i].Params[2].FloatValue);
                        transform = transform * Math.Matrix.RotateY(Utils.DegreesToRadians(-_actionSection.Lines[i].Params[4].FloatValue + _actionSection.Lines[i].Params[8].FloatValue));
                        transform = transform * Math.Matrix.Translate(_actionSection.Lines[i].Params[5].FloatValue,
                                                                      _actionSection.Lines[i].Params[7].FloatValue,
                                                                      _actionSection.Lines[i].Params[6].FloatValue);

                        act.Transformation = transform;
                    }
                    else
                    {
                        act.Transformation = Math.Matrix.Identity;
                    }


                    if (act.Model == null)
                    {
                        continue;
                    }

                    // add the act file to the list
                    bool added = false;
                    for (int j = 0; j < _acts.Count; j++)
                    {
                        if (_acts[j].HasValue == false)
                        {
                            _acts[j] = act;
                            added    = true;
                            break;
                        }
                    }
                    if (added == false)
                    {
                        _acts.Add(act);
                    }
                }
            }

            // animate models using ACT files
            for (int i = 0; i < _acts.Count; i++)
            {
                if (_acts[i].HasValue)
                {
                    _acts[i].Value.Model.TempTransform = _acts[i].Value.Transformation;

                    if (_acts[i].Value.Act.Animate(_acts[i].Value.Model, timeSinceStart, duration, true, _acts[i].Value.IsAbsolute) == false)
                    {
                        _acts[i] = null;
                    }
                }
            }
        }
Exemplo n.º 17
0
        public bool ConvertAllObjects(BulletFile file)
        {
            _shapeMap.Clear();
            _bodyMap.Clear();

            foreach (byte[] bvhData in file.Bvhs)
            {
                OptimizedBvh bvh = CreateOptimizedBvh();

                if ((file.Flags & FileFlags.DoublePrecision) != 0)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    // QuantizedBvhData is parsed in C++, so we need to actually fix pointers
                    GCHandle bvhDataHandle    = GCHandle.Alloc(bvhData, GCHandleType.Pinned);
                    IntPtr   bvhDataPinnedPtr = bvhDataHandle.AddrOfPinnedObject();

                    IntPtr contiguousNodesHandlePtr          = IntPtr.Zero;
                    IntPtr quantizedContiguousNodesHandlePtr = IntPtr.Zero;
                    IntPtr subTreeInfoHandlePtr = IntPtr.Zero;

                    using (var stream = new MemoryStream(bvhData))
                    {
                        using (var reader = new BulletReader(stream))
                        {
                            long contiguousNodesPtr          = reader.ReadPtr(QuantizedBvhFloatData.Offset("ContiguousNodesPtr"));
                            long quantizedContiguousNodesPtr = reader.ReadPtr(QuantizedBvhFloatData.Offset("QuantizedContiguousNodesPtr"));
                            long subTreeInfoPtr = reader.ReadPtr(QuantizedBvhFloatData.Offset("SubTreeInfoPtr"));

                            using (var writer = new BulletWriter(stream))
                            {
                                if (contiguousNodesPtr != 0)
                                {
                                    GCHandle contiguousNodesHandle = GCHandle.Alloc(file.LibPointers[contiguousNodesPtr], GCHandleType.Pinned);
                                    contiguousNodesHandlePtr = GCHandle.ToIntPtr(contiguousNodesHandle);
                                    stream.Position          = QuantizedBvhFloatData.Offset("ContiguousNodesPtr");
                                    writer.Write(contiguousNodesHandle.AddrOfPinnedObject());
                                }
                                if (quantizedContiguousNodesPtr != 0)
                                {
                                    GCHandle quantizedContiguousNodesHandle = GCHandle.Alloc(file.LibPointers[quantizedContiguousNodesPtr], GCHandleType.Pinned);
                                    quantizedContiguousNodesHandlePtr = GCHandle.ToIntPtr(quantizedContiguousNodesHandle);
                                    stream.Position = QuantizedBvhFloatData.Offset("QuantizedContiguousNodesPtr");
                                    writer.Write(quantizedContiguousNodesHandle.AddrOfPinnedObject());
                                }
                                if (subTreeInfoPtr != 0)
                                {
                                    GCHandle subTreeInfoHandle = GCHandle.Alloc(file.LibPointers[subTreeInfoPtr], GCHandleType.Pinned);
                                    subTreeInfoHandlePtr = GCHandle.ToIntPtr(subTreeInfoHandle);
                                    stream.Position      = QuantizedBvhFloatData.Offset("SubTreeInfoPtr");
                                    writer.Write(subTreeInfoHandle.AddrOfPinnedObject());
                                }
                            }
                        }
                    }

                    bvh.DeSerializeFloat(bvhDataPinnedPtr);
                    bvhDataHandle.Free();

                    if (contiguousNodesHandlePtr != IntPtr.Zero)
                    {
                        GCHandle.FromIntPtr(contiguousNodesHandlePtr).Free();
                    }
                    if (quantizedContiguousNodesHandlePtr != IntPtr.Zero)
                    {
                        GCHandle.FromIntPtr(quantizedContiguousNodesHandlePtr).Free();
                    }
                    if (subTreeInfoHandlePtr != IntPtr.Zero)
                    {
                        GCHandle.FromIntPtr(subTreeInfoHandlePtr).Free();
                    }
                }

                foreach (KeyValuePair <long, byte[]> lib in file.LibPointers)
                {
                    if (lib.Value == bvhData)
                    {
                        _bvhMap.Add(lib.Key, bvh);
                        break;
                    }
                }
            }

            foreach (byte[] shapeData in file.CollisionShapes)
            {
                CollisionShape shape = ConvertCollisionShape(shapeData, file.LibPointers);
                if (shape != null)
                {
                    foreach (KeyValuePair <long, byte[]> lib in file.LibPointers)
                    {
                        if (lib.Value == shapeData)
                        {
                            _shapeMap.Add(lib.Key, shape);
                            break;
                        }
                    }

                    using (var stream = new MemoryStream(shapeData, false))
                    {
                        using (var reader = new BulletReader(stream))
                        {
                            long namePtr = reader.ReadPtr(CollisionShapeFloatData.Offset("Name"));
                            if (namePtr != 0)
                            {
                                byte[] nameData = file.LibPointers[namePtr];
                                int    length   = Array.IndexOf(nameData, (byte)0);
                                string name     = System.Text.Encoding.ASCII.GetString(nameData, 0, length);
                                _objectNameMap.Add(shape, name);
                                _nameShapeMap.Add(name, shape);
                            }
                        }
                    }
                }
            }

            foreach (byte[] solverInfoData in file.DynamicsWorldInfo)
            {
                if ((file.Flags & FileFlags.DoublePrecision) != 0)
                {
                    //throw new NotImplementedException();
                }
                else
                {
                    //throw new NotImplementedException();
                }
            }

            foreach (byte[] bodyData in file.RigidBodies)
            {
                if ((file.Flags & FileFlags.DoublePrecision) != 0)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    ConvertRigidBodyFloat(bodyData, file.LibPointers);
                }
            }

            foreach (byte[] colObjData in file.CollisionObjects)
            {
                if ((file.Flags & FileFlags.DoublePrecision) != 0)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    using (var colObjStream = new MemoryStream(colObjData, false))
                    {
                        using (var colObjReader = new BulletReader(colObjStream))
                        {
                            long           shapePtr       = colObjReader.ReadPtr(CollisionObjectFloatData.Offset("CollisionShape"));
                            CollisionShape shape          = _shapeMap[shapePtr];
                            Math.Matrix    startTransform = colObjReader.ReadMatrix(CollisionObjectFloatData.Offset("WorldTransform"));
                            long           namePtr        = colObjReader.ReadPtr(CollisionObjectFloatData.Offset("Name"));
                            string         name           = null;
                            if (namePtr != 0)
                            {
                                byte[] nameData = file.FindLibPointer(namePtr);
                                int    length   = Array.IndexOf(nameData, (byte)0);
                                name = System.Text.Encoding.ASCII.GetString(nameData, 0, length);
                            }
                            CollisionObject colObj = CreateCollisionObject(ref startTransform, shape, name);
                            _bodyMap.Add(colObjData, colObj);
                        }
                    }
                }
            }

            foreach (byte[] constraintData in file.Constraints)
            {
                var stream = new MemoryStream(constraintData, false);
                using (var reader = new BulletReader(stream))
                {
                    long collisionObjectAPtr = reader.ReadPtr(TypedConstraintFloatData.Offset("RigidBodyA"));
                    long collisionObjectBPtr = reader.ReadPtr(TypedConstraintFloatData.Offset("RigidBodyB"));

                    RigidBody a = null, b = null;

                    if (collisionObjectAPtr != 0)
                    {
                        if (!file.LibPointers.ContainsKey(collisionObjectAPtr))
                        {
                            a = TypedConstraint.GetFixedBody();
                        }
                        else
                        {
                            byte[] coData = file.LibPointers[collisionObjectAPtr];
                            a = RigidBody.Upcast(_bodyMap[coData]);
                            if (a == null)
                            {
                                a = TypedConstraint.GetFixedBody();
                            }
                        }
                    }

                    if (collisionObjectBPtr != 0)
                    {
                        if (!file.LibPointers.ContainsKey(collisionObjectBPtr))
                        {
                            b = TypedConstraint.GetFixedBody();
                        }
                        else
                        {
                            byte[] coData = file.LibPointers[collisionObjectBPtr];
                            b = RigidBody.Upcast(_bodyMap[coData]);
                            if (b == null)
                            {
                                b = TypedConstraint.GetFixedBody();
                            }
                        }
                    }

                    if (a == null && b == null)
                    {
                        stream.Dispose();
                        continue;
                    }

                    if ((file.Flags & FileFlags.DoublePrecision) != 0)
                    {
                        throw new NotImplementedException();
                    }
                    else
                    {
                        ConvertConstraintFloat(a, b, constraintData, file.Version, file.LibPointers);
                    }
                }
                stream.Dispose();
            }

            return(true);
        }
Exemplo n.º 18
0
 public abstract void SetParameter(string name, Math.Matrix parameter);