Beispiel #1
0
        private void RenderNode(SceneGraph Node, Camera Camera, SlimDX.Matrix ProjMatrix, int indexOffset, int vertexOffset, out int indicesConsumed, out int verticesConsumed)
        {
            var ic = indexOffset;
            var vc = vertexOffset;

            if (Node.Renderable != null)
            {
                WorldViewProj = Node.WorldTransform * Camera.GetViewMatrix() * ProjMatrix;
                CPO_WorldViewProj.SetMatrix(WorldViewProj);

                int nIndices = Node.Renderable.GetIndexList(EffectName()).Length;
                int nVerts   = Node.Renderable.GetVertexList(EffectName()).Length;

                // TODO KAM: This is horribly inefficient, change this!
                ImmediateContext.DrawIndexed(nIndices, indexOffset, vertexOffset);

                ic += nIndices;
                vc += nVerts;
            }

            foreach (var Child in Node.Children)
            {
                int cic, cvc;
                RenderNode(Child.Value, Camera, ProjMatrix, indexOffset + ic, vertexOffset + vc, out cic, out cvc);
                ic += cic;
                vc += cvc;
            }

            indicesConsumed  = ic;
            verticesConsumed = vc;
        }
Beispiel #2
0
        public void GenerateSceneGraph()
        {
            if (regionMap != null)
            {
                DestroyImmediate(regionMap);
            }

            // Merge all feature meshes
            List <FeatureMesh> features = new List <FeatureMesh>();

            foreach (var task in tasks)
            {
                if (task.Generation == generation)
                {
                    features.AddRange(task.Data);
                }
            }

            tasks.Clear();
            nTasksForArea = 0;

            regionMap = new GameObject(RegionName);
            var sceneGraph = new SceneGraph(regionMap, GroupOptions, GameObjectOptions, features);

            sceneGraph.Generate();
        }
        public void Render(SceneGraph SceneGraph, Camera Camera, Matrix ProjMatrix)
        {
            // Set input assembler information
            ImmediateContext.InputAssembler.InputLayout       = InputLayout;
            ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            // Build vertex and index buffer
            // TODO KAM: If nothing has changed, don't re-build the buffers maybe? But how to tell...
            var verts   = GetAllVertices(SceneGraph);
            var indices = GetAllIndices(SceneGraph);

            var vertBufferDesc = new BufferDescription(BasicEffectVertex.Stride * verts.Length,
                                                       ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            Util.ReleaseCom(ref VertexBuffer);
            VertexBuffer = new SlimDX.Direct3D11.Buffer(Device, new DataStream(verts, false, false), vertBufferDesc);

            var indexBufferDesc = new BufferDescription(sizeof(uint) * indices.Length,
                                                        ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            Util.ReleaseCom(ref IndexBuffer);
            IndexBuffer = new SlimDX.Direct3D11.Buffer(Device, new DataStream(indices, false, false), indexBufferDesc);

            // Set vertex and index buffers
            ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(VertexBuffer, BasicEffectVertex.Stride, 0));
            ImmediateContext.InputAssembler.SetIndexBuffer(IndexBuffer, SlimDX.DXGI.Format.R32_UInt, 0);

            // Render all nodes!
            Pass = EffectTechnique.GetPassByIndex(0);
            int a, b;

            RenderNode(SceneGraph, Camera, ProjMatrix, 0, 0, out a, out b);
        }
Beispiel #4
0
 public SetProjectionMatrix(SceneGraph sceneGraph, float fieldOfViewVerticalDegrees, float nearPlane, float farPlane)
 {
     _fieldOfViewVerticalRadians = MathHelper.DegreesToRadians(fieldOfViewVerticalDegrees);
     _nearPlane  = nearPlane;
     _farPlane   = farPlane;
     _sceneGraph = sceneGraph;
 }
Beispiel #5
0
        private void IterateHierarchyForSkeletonRecursive(SceneGraph curNode, List<SkeletonJoint> jointList, int parentId)
        {
            switch (curNode.NodeType)
            {
                case J3DFormat.HierarchyDataTypes.NewNode:
                    parentId = jointList.Count - 1;
                    break;

                case J3DFormat.HierarchyDataTypes.Joint:
                    J3DFormat.Joint j3dJoint = _file.Joints.GetJoint(curNode.DataIndex);
                    SkeletonJoint joint = new SkeletonJoint();
                    joint.Name = _file.Joints.GetString(_file.Joints.GetStringTableEntry(_file.Joints.GetStringIndex(curNode.DataIndex))); //Todo: You have got to be kidding me.

                    Vector3 jointAngles = j3dJoint.GetRotation().ToDegrees();
                    joint.Rotation = Matrix4.CreateRotationX(MathHelper.DegreesToRadians(jointAngles.X)) * Matrix4.CreateRotationY(MathHelper.DegreesToRadians(jointAngles.Y)) * Matrix4.CreateRotationZ(MathHelper.DegreesToRadians(jointAngles.Z));

                    //joint.Rotation.Normalize();
                    joint.Position = j3dJoint.GetTranslation();
                    joint.ParentId = parentId;
                    joint.Scale = j3dJoint.GetScale();
                    Console.WriteLine("{0} - Pos: {1} Rot: {2}", joint, joint.Position, jointAngles);

                    jointList.Add(joint);
                    break;
            }

            foreach (SceneGraph child in curNode.Children)
            {
                IterateHierarchyForSkeletonRecursive(child, jointList, parentId);
            }
        }
Beispiel #6
0
        public Entities(GLProgram program, SceneGraph scene)
            : base(program)
        {
            var numPointLights = 0;
            var plights        = new LightingShaders.PointLight[4];

            using (program.Scope())
            {
                foreach (var pointLight in scene.Root.Traverse().OfType <PointLight> ())
                {
                    plights[numPointLights++] = new LightingShaders.PointLight
                    {
                        position             = pointLight.Position,
                        intensity            = pointLight.Intensity,
                        linearAttenuation    = pointLight.LinearAttenuation,
                        quadraticAttenuation = pointLight.QuadraticAttenuation
                    };
                }
                pointLights &= plights;

                var samp = new Sampler2D[4];
                for (int i = 0; i < samp.Length; i++)
                {
                    samp[i] = new Sampler2D(i + 1).LinearFiltering().ClampToEdges(Axes.All);
                }
                samplers   &= samp;
                diffuseMap &= new SamplerCube(5).LinearFiltering().ClampToEdges(Axes.All);

                lighting   = new LightingUniforms(program, scene);
                transforms = new TransformUniforms(program);
                shadows    = new CascadedShadowUniforms(program,
                                                        new Sampler2DArray(0).LinearFiltering().ClampToEdges(Axes.All));
            }
        }
    protected void FillSceneGraphFloatingBars(SceneGraph scene)
    {
        int    rowCount  = this.Data.GetRowCount();
        double boxHeight = ((this.YAxis.MapMaximum - this.YAxis.MapMinimum) / rowCount) / 2;

        for (int r = 0; r < rowCount; r++)
        {
            DateTime  start    = (DateTime)this.Data.GetObjectValue(r, this.StartDateTimeColumnNumber);
            DateTime  end      = (DateTime)this.Data.GetObjectValue(r, this.EndDateTimeColumnNumber);
            int       boxX     = (int)this.XAxis.Map(start);
            int       boxY     = (int)this.YAxis.Map(r) + (int)(boxHeight / 2);
            int       boxWidth = (int)(this.XAxis.Map(end) - this.XAxis.Map(start));
            Rectangle boxRect  = new Rectangle(boxX, boxY, boxWidth, (int)boxHeight);
            Box       b        = new Box(boxRect);
            b.PE.Fill = this.ChartColorModel.getFillColor(r, r, (double)start.Ticks);

            b.Caps   = PCaps.HitTest | PCaps.Skin | PCaps.Tooltip;
            b.Column = this.StartDateTimeColumnNumber;
            b.Row    = r;
            b.Chart  = ChartType.BarChart;
            b.Layer  = this.ChartCore.GetChartLayer();
            b.Value  = 12345;
            scene.Add(b);
        }
    }
    public static void CreateSceneTree()
    {
        SceneGraph instance = ScriptableObject.CreateInstance <SceneGraph>();

        AssetDatabase.CreateAsset(instance, "Assets/Scripts/Scriptable/SceneTree.asset");
        AssetDatabase.SaveAssets();
    }
        public void SpawnAtMe_Position()
        {
            SceneGraph        graph       = BuildSceneGraph();
            Vector2           objPosition = new Vector2(32, 64);
            GameObjectCounter obj         = new GameObjectCounter();

            obj.Position = objPosition;

            GameObject childObj = new GameObject();

            childObj.Position   = new Vector2(16, 16);
            childObj.SceneGraph = graph;
            obj.AddChild(childObj);

            graph.Add(obj);
            graph.Update();

            GameObjectCounter spawn = new GameObjectCounter();

            childObj.SpawnAtMe(spawn);

            graph.Update();

            Assert.That(spawn.Position, Is.EqualTo(childObj.AbsolutePosition));
            Assert.That(spawn.Position, Is.EqualTo(new Vector2(48f, 80f)));
        }
        /// <summary>
        ///		Loads this tilemap segment node from a given binary reader.
        /// </summary>
        /// <param name="reader">Binary reader to load this tilemap segment node from.</param>
        public override void Load(BinaryReader reader)
        {
            // Load all the basic entity details.
            base.Load(reader);

            // Load all the tilemap specific details.
            _width      = reader.ReadInt32();
            _height     = reader.ReadInt32();
            _tileWidth  = reader.ReadInt16();
            _tileHeight = reader.ReadInt16();

            // Load in all the tileset in this map.
            _tileData = new TileNode[_width, _height];
            for (int x = 0; x < _width; x++)
            {
                for (int y = 0; y < _height; y++)
                {
                    _tileData[x, y] = new TileNode();
                    if (_tileData[x, y].Parent != null)
                    {
                        _tileData[x, y].Parent.RemoveChild(_tileData[x, y]);
                    }
                    _tileData[x, y].Parent = this;
                    SceneGraph.AttachNode(_tileData[x, y]);
                    _tileData[x, y].Load(reader);
                }
            }
        }
Beispiel #11
0
        public OpenGLSceneProcessor(IServiceProvider serviceProvider, IRenderWindow renderWindow, SceneGraph sceneGraph)
        {
            _serviceProvider          = serviceProvider;
            _cancellationTokenManager = _serviceProvider.GetRequiredService <CancellationTokenSource>();
            _logger         = _serviceProvider.GetRequiredService <ILogger <RenderWindow> >();
            _shaderCompiler = _serviceProvider.GetRequiredService <IShaderCompiler>();
            _textureLoader  = _serviceProvider.GetRequiredService <ITextureLoader>();

            _renderWindow   = renderWindow; // This cannot be passed via the service provider otherwise there will be a cycle in the DI graph
            _sceneGraph     = sceneGraph;
            _renderList     = new LinkedList <IRenderCommand>();
            _renderInfo     = new RenderInfo();
            _requestPicking = null;

            GL.LoadBindings(new GLFWBindingsContext());

            // Get human readable log messages during debugging
            if (Debugger.IsAttached)
            {
                GL.Enable(EnableCap.DebugOutput);
                _debugProc = DebugMessageCallback;
                _gcHandle  = GCHandle.Alloc(_debugProc);
                GL.DebugMessageCallback(_debugProc, IntPtr.Zero);
            }

            GL.Enable(EnableCap.DepthTest);

            // Save default frame buffer id for later blitting
            GL.GetInteger(GetPName.FramebufferBinding, out _defaultFrameBufferId);
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, _defaultFrameBufferId);

            InitFrameBuffer(640, 360);
        }
        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            _bitmapFont = Content.Load <BitmapFont>("Fonts/montserrat-32");

            var viewportAdapter = new BoxingViewportAdapter(Window, GraphicsDevice, 800, 480);

            _camera = new OrthographicCamera(viewportAdapter)
            {
                Zoom = 2.0f
            };
            _sceneGraph = new SceneGraph();

            var carHullTexture  = Content.Load <Texture2D>("Textures/car-hull");
            var carHullSprite   = new Sprite(carHullTexture);
            var carWheelTexture = Content.Load <Texture2D>("Textures/car-wheel");
            var carWheelSprite  = new Sprite(carWheelTexture);

            _carNode = new SceneNode("car-hull", viewportAdapter.Center.ToVector2());
            _carNode.Entities.Add(new SpriteEntity(carHullSprite));

            _leftWheelNode = new SceneNode("left-wheel", new Vector2(-29, 17));
            _leftWheelNode.Entities.Add(new SpriteEntity(carWheelSprite));

            _rightWheelNode = new SceneNode("right-wheel", new Vector2(40, 17));
            _rightWheelNode.Entities.Add(new SpriteEntity(carWheelSprite));

            _carNode.Children.Add(_rightWheelNode);
            _carNode.Children.Add(_leftWheelNode);
            _sceneGraph.RootNode.Children.Add(_carNode);
        }
Beispiel #13
0
        public static Reaction <Camera> Renderer(SceneGraph sceneGraph)
        {
            _shader = PassThrough;

            return(React.By <Camera> (Render)
                   .Program(_shader));
        }
Beispiel #14
0
        private void IterateHierarchyForSkeletonRecursive(SceneGraph curNode, List <SkeletonJoint> jointList, int parentId)
        {
            switch (curNode.NodeType)
            {
            case J3DFormat.HierarchyDataTypes.NewNode:
                parentId = jointList.Count - 1;
                break;

            case J3DFormat.HierarchyDataTypes.Joint:
                J3DFormat.Joint j3dJoint = _file.Joints.GetJoint(curNode.DataIndex);
                SkeletonJoint   joint    = new SkeletonJoint();
                joint.Name = _file.Joints.GetString(_file.Joints.GetStringTableEntry(_file.Joints.GetStringIndex(curNode.DataIndex)));     //Todo: You have got to be kidding me.

                Vector3 jointAngles = j3dJoint.GetRotation().ToDegrees();
                joint.Rotation = Matrix4.CreateRotationX(MathHelper.DegreesToRadians(jointAngles.X)) * Matrix4.CreateRotationY(MathHelper.DegreesToRadians(jointAngles.Y)) * Matrix4.CreateRotationZ(MathHelper.DegreesToRadians(jointAngles.Z));

                //joint.Rotation.Normalize();
                joint.Position = j3dJoint.GetTranslation();
                joint.ParentId = parentId;
                joint.Scale    = j3dJoint.GetScale();
                Console.WriteLine("{0} - Pos: {1} Rot: {2}", joint, joint.Position, jointAngles);

                jointList.Add(joint);
                break;
            }

            foreach (SceneGraph child in curNode.Children)
            {
                IterateHierarchyForSkeletonRecursive(child, jointList, parentId);
            }
        }
Beispiel #15
0
        private void CreateSceneGraph()
        {
            _sceneGraph = new SceneGraph();

            _camera = new Camera(_sceneGraph,
                                 position: new Vec3(0f, 0f, 1f),
                                 target: new Vec3(0f, 0f, 0f),
                                 upDirection: new Vec3(0f, 1f, 0f),
                                 frustum: new ViewingFrustum(FrustumKind.Perspective, 1f, 1f, -1f, -10000f),
                                 aspectRatio: 1f);

            var rect = Quadrilateral <MaterialVertex> .Rectangle(100f, 100f);

            rect.ApplyTextureFront(1f, new Vec2(0f), new Vec2(1f));
            rect.UpdateTangents(BeginMode.Triangles);

            _diffuseMap = new Texture(TextureTarget.Texture2D);
            _normalMap  = new Texture(TextureTarget.Texture2D);
            _heightMap  = new Texture(TextureTarget.Texture2D);

            var texturePanel = MaterialPanel <TexturedVertex> .Movable(_sceneGraph, false,
                                                                       new Vec2 (0.4f, 0.8f), new Vec2i (1));

            var guiWindow = ControlPanel <TexturedVertex> .Movable(_sceneGraph,
                                                                   Editor (new Vec2i(1024), @"Materials\Ground.xml", texturePanel.Node),
                                                                   new Vec2i (650, 550), new Vec2 (-0.99f, 0.99f));

            _mesh = new Mesh <MaterialVertex> (_sceneGraph, rect);
            _sceneGraph.Root.Add(_camera, _mesh, guiWindow, texturePanel);
        }
Beispiel #16
0
 public void Inject(object reference)
 {
     if (reference is SceneGraph)
     {
         Graph = reference as SceneGraph;
     }
 }
Beispiel #17
0
        protected override async ValueTask Init()
        {
            this.AddService(new InputService());

            var collisionService = new CollisionService(this, new Size(64, 64));

            this.AddService(collisionService);

            var sceneGraph = new SceneGraph(this);

            this.AddService(sceneGraph);

            var player = BuildPlayer();

            sceneGraph.Root.AddChild(player);

            for (var i = 0; i != 6; ++i)
            {
                AddAsteroid(sceneGraph);
            }

            var context = await _canvas.CreateCanvas2DAsync();

            var renderService = new RenderService(this, context);

            this.AddService(renderService);
        }
 public void MoveObjectToInFrontOfCamera(SceneGraph Node)
 {
     Cameras.Camera SceneCamera = OutsideSimulatorApp.GetInstance().SceneCamera;
     Vector3 lav = (SceneCamera.LookAt - SceneCamera.Position);
     lav.Normalize();
     Node.Translation = OutsideSimulatorApp.GetInstance().SceneCamera.Position + lav * frontDist;
 }
        public void IgnoreCollision_NoClip()
        {
            SceneGraph graph = BuildSceneGraph();

            GameObjectCounter obj1 = new GameObjectCounter()
            {
                NoClip = true
            };

            obj1.SetCollisionSize(32, 32);
            graph.Add(obj1);

            GameObjectCounter obj2 = new GameObjectCounter()
            {
                NoClip = false
            };

            obj2.SetCollisionSize(32, 32);
            graph.Add(obj2);

            graph.Update();

            Assert.That(GetObjectTotals(graph).CollisionTestCount, Is.EqualTo(0));
            Assert.That(GetObjectTotals(graph).CollisionCount, Is.EqualTo(0));
        }
        public void Collision_InjectObject()
        {
            SceneGraph graph = BuildSceneGraph();

            GameObjectCollisionSpawn obj1 = new GameObjectCollisionSpawn(graph)
            {
                NoClip = false, SceneGraph = graph
            };

            obj1.SetCollisionSize(32, 32);
            graph.Add(obj1);

            GameObjectCollisionSpawn obj2 = new GameObjectCollisionSpawn(graph)
            {
                NoClip = false, SceneGraph = graph
            };

            obj2.SetCollisionSize(32, 32);
            graph.Add(obj2);

            graph.Update();
            graph.Draw(null);

            Assert.That(graph.RootGraph.Count, Is.EqualTo(4));
            Assert.That(GetObjectTotals(graph).CollisionTestCount, Is.EqualTo(2));
            Assert.That(GetObjectTotals(graph).CollisionCount, Is.EqualTo(2));
            Assert.That(GetObjectTotals(graph).UpdateCount, Is.EqualTo(2));
            Assert.That(GetObjectTotals(graph).DrawCount, Is.EqualTo(4));
        }
        public void CalculateTransforms_BeforeCollisionCheck()
        {
            SceneGraph graph          = BuildSceneGraph();
            Vector2    parentPosition = new Vector2(32, 64);
            GameObject obj            = new GameObject();

            obj.Position = parentPosition;
            obj.NoClip   = false;
            obj.SetCollisionSize(16, 16);

            Vector2    childPosition = new Vector2(96, 128);
            GameObject childObj      = new GameObject();

            childObj.Position = childPosition;
            childObj.NoClip   = false;
            childObj.SetCollisionSize(16, 16);

            obj.AddChild(childObj);

            GameObjectCounter collisionObj = new GameObjectCounter();

            collisionObj.Position = parentPosition + childPosition;
            collisionObj.NoClip   = false;
            collisionObj.SetCollisionSize(16, 16);

            graph.Add(obj);
            graph.Add(collisionObj);
            graph.Update();

            Assert.That(collisionObj.Stats.CollisionCount, Is.EqualTo(1));
        }
        public void Draw_Empty()
        {
            SceneGraph graph = BuildSceneGraph();

            graph.Update();
            graph.Draw(null);
        }
Beispiel #23
0
        private void SampleGraphicsControl_GraphicsContextCreated(object sender, GraphicsControlEventArgs e)
        {
            GraphicsContext ctx         = e.Context;
            GraphicsSurface framebuffer = e.Framebuffer;

#if DEBUG
            _GeometryClipmapObject = new GeometryClipmapObject(6, 7, _BlockUnit);
#else
            _GeometryClipmapObject = new GeometryClipmapObject(9, 11, _BlockUnit);
#endif

            string workingDir = Directory.GetCurrentDirectory();

            _GeometryClipmapObject.SetTerrainElevationFactory(Path.Combine(workingDir, @"..\..\..\Data\Terrain.vrt"), 45.5, 10.5);

            _GeometryClipmapScene = new SceneGraph();
            _GeometryClipmapScene.AddChild(new SceneGraphCameraObject());
            _GeometryClipmapScene.AddChild(_GeometryClipmapObject);
            _GeometryClipmapScene.Create(ctx);

            // Set projection
            _GeometryClipmapScene.CurrentView.ProjectionMatrix = new PerspectiveProjectionMatrix(
                _ViewFov / 16.0f * 9.0f,
                (float)ClientSize.Width / (float)ClientSize.Height,
                1.0f, _ViewDepth
                );;

            // Clear color
            framebuffer.SetClearColor(new ColorRGBAF(0.0f, 0.0f, 0.0f));
        }
Beispiel #24
0
        /// <summary>
        /// Allocate resources for rendering.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ObjectsControl_ContextCreated(object sender, GlControlEventArgs e)
        {
            // Wrap GL context with GraphicsContext
            _Context = new GraphicsContext(e.DeviceContext, e.RenderContext);

            // Scene
            _CubeScene = new SceneGraph(SceneGraphFlags.None)
            {
                SceneRoot   = new SceneObjectGeometry(),
                CurrentView = new SceneObjectCamera()
            };

            // Root object
            // _CubeScene.SceneRoot.ObjectState.DefineState(new DepthTestState(DepthFunction.Less));

            // Camera object
            _CubeScene.SceneRoot.Link(_CubeScene.CurrentView);

            // Horizontal plane
            _CubeScene.SceneRoot.Link(CreatePlane());

            // Create scene resource
            _CubeScene.Create(_Context);

            Gl.ClearColor(0.1f, 0.1f, 0.1f, 0.0f);

            Gl.Enable(EnableCap.Multisample);
        }
Beispiel #25
0
        public override void Load(byte[] data)
        {
            _file         = new J3DFormat();
            _renderList   = new List <RenderBatch>();
            _textureCache = new Dictionary <int, int>();
            _file.Load(data);
            _dataCache = data;

            Selected = false;


            /* Dump info for debugging */
            Console.WriteLine("Model: {0}, Vertex Count: {1} Packet Count: {2} Joint Count: {3}", FileName, _file.Info.GetVertexCount(), _file.Info.GetPacketCount(), _file.Joints.GetJointCount());
            Console.WriteLine("Envelope Count: {0} Draw Count: {1}", _file.Envelopes.GetEnvelopeCount(), _file.Draw.GetDrawCount());

            //Extract the data from the file format into something we can use.
            _vertDataBind = BuildVertexArraysFromFile();

            //Build our scene-graph so we can iterate through it.
            _root     = BuildSceneGraphFromInfo();
            _skeleton = BuildSkeletonFromHierarchy();

            //Generate our VBO, and upload the data
            GL.GenBuffers(1, out _glVbo);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _glVbo);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(_vertDataBind.Count * 9 * 4), _vertDataBind.ToArray(),
                          BufferUsageHint.StaticDraw);

            //Make sure we get drawn
            J3DRenderer.Instance.AddRenderable(this);
        }
Beispiel #26
0
        public override void Load(byte[] data)
        {
            _file = new J3DFormat();
            _renderList = new List<RenderBatch>();
            _textureCache = new Dictionary<int, int>();
            _file.Load(data);
            _dataCache = data;

            Selected = false;


            /* Dump info for debugging */
            Console.WriteLine("Model: {0}, Vertex Count: {1} Packet Count: {2} Joint Count: {3}", FileName, _file.Info.GetVertexCount(), _file.Info.GetPacketCount(), _file.Joints.GetJointCount());
            Console.WriteLine("Envelope Count: {0} Draw Count: {1}", _file.Envelopes.GetEnvelopeCount(), _file.Draw.GetDrawCount());

            //Extract the data from the file format into something we can use.
            _vertDataBind = BuildVertexArraysFromFile();

            //Build our scene-graph so we can iterate through it.
            _root = BuildSceneGraphFromInfo();
            _skeleton = BuildSkeletonFromHierarchy();

            //Generate our VBO, and upload the data
            GL.GenBuffers(1, out _glVbo);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _glVbo);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(_vertDataBind.Count * 9 * 4), _vertDataBind.ToArray(),
                BufferUsageHint.StaticDraw);

            //Make sure we get drawn
            J3DRenderer.Instance.AddRenderable(this);
        }
Beispiel #27
0
        private void AddAsteroid(SceneGraph sceneGraph)
        {
            var asteroid = new GameObject();

            var spriteSheet = _assetsResolver.Get <SpriteSheet>("assets/sheet.json");
            var sprite      = spriteSheet.Get("meteorBrown_big1.png");

            var transform = asteroid.Components.Add <TransformComponent>();

            var w  = (double)_canvas.Width;
            var rx = MathUtils.Random.NextDouble(0, .35, .65, 1);
            var tx = MathUtils.Normalize(rx, 0, 1, -1, 1);

            transform.Local.Position.X = (float)(tx * w / 2 + w / 2);

            var h  = (double)_canvas.Height;
            var ry = MathUtils.Random.NextDouble(0, .35, .65, 1);
            var ty = MathUtils.Normalize(ry, 0, 1, -1, 1);

            transform.Local.Position.Y = (float)(ty * h / 2 + h / 2);

            var spriteRenderer = asteroid.Components.Add <SpriteRenderComponent>();

            spriteRenderer.Sprite = sprite;

            var bbox = asteroid.Components.Add <BoundingBoxComponent>();

            bbox.SetSize(sprite.Bounds.Size);

            asteroid.Components.Add <AsteroidBrain>();

            sceneGraph.Root.AddChild(asteroid);
        }
Beispiel #28
0
 protected internal SceneMeshEntity(SceneGraph ownr, string name)
     : base(name, ownr)
 {
     VertexIndexes = new List<Int3>();
     TextureIndexes = new List<Int3>();
     NormalIndexes = new List<Int3>();
 }
Beispiel #29
0
    public override void OnInspectorGUI()
    {
        SceneGraph sceneGraph = (SceneGraph)target; //Script del grafo


        if (GUILayout.Button("Crear vertice"))
        {
            sceneGraph.AddVertex();
        }

        //Crear arcos



        DrawDefaultInspector(); //mostrar listas
        GUILayout.BeginHorizontal();

        EditorGUIUtility.fieldWidth = 5;

        GUILayout.Label("V1");
        vertice1 = EditorGUILayout.IntField(vertice1);
        GUILayout.Label("V2");
        vertice2 = EditorGUILayout.IntField(vertice2);

        GUILayout.EndHorizontal();

        if (GUILayout.Button("Crear arco"))
        {
            sceneGraph.AddArc(vertice1, vertice2);
        }

        GUILayout.BeginHorizontal();
        GUILayout.Label("Vertice");
        verticeElim = EditorGUILayout.IntField(verticeElim);
        if (GUILayout.Button("Eliminar vertice"))
        {
            sceneGraph.RemoveVertex(verticeElim);
        }

        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        GUILayout.Label("V1");
        arcoElim1 = EditorGUILayout.IntField(arcoElim1);
        GUILayout.Label("V2");
        arcoElim2 = EditorGUILayout.IntField(arcoElim2);
        if (GUILayout.Button("Eliminar arco"))
        {
            sceneGraph.RemoveArc(arcoElim1, arcoElim2);
        }

        GUILayout.EndHorizontal();


        if (GUILayout.Button("Construir grafo"))
        {
            sceneGraph.CreateGraph();
        }
    }
Beispiel #30
0
 public SceneItem(Session session, SceneGraph graph)
 {
     m_Session       = session;
     m_Graph         = graph;
     m_Scene         = graph.Scene;
     m_EntityManager = session.GetManager <IWorldManager>().EntityManager;
     m_SceneManager  = session.GetManager <IEditorSceneManagerInternal>();
 }
Beispiel #31
0
 public SelectionHandler(SceneGraph sg, InputHandler inputHandler)
 {
     this.sg                 = sg;
     this.inputHandler       = inputHandler;
     Validator               = null;
     inputHandler.MouseDown += MouseDown;
     inputHandler.KeyDown   += KeyDown;
 }
Beispiel #32
0
        protected override void CreateDefaultCamera()
        {
            var camComponent = new ArcBallCameraComponent(Vector3.Zero, 10.0f, 45.0f, -45.0f, 0.0f, RenderConfig.ScreenSize, 0.1f, 500.0f);

            CurrentCamera = new CameraActor(camComponent);

            SceneGraph.AddActor(CurrentCamera);
        }
 protected void FillSceneGraphXAxis(SceneGraph scene)
 {
     #region X axis
     this.XAxis.FillSceneGraph(scene);
     Line l = new Line(new Point((int)XAxis.MapMinimum, (int)YAxis.MapMinimum), new Point((int)XAxis.MapMinimum, (int)YAxis.MapMaximum), new LineStyle());
     scene.Add(l);
     #endregion
 }
        /// <summary>
        /// Compiles a Scene Graph into XML.
        /// </summary>
        public static string CompileXML(SceneGraph graph)
        {
            X3DSceneGraphXMLSerializer serializer;

            serializer = new X3DSceneGraphXMLSerializer(graph.GetRoot());

            return(serializer.Serialize());
        }
Beispiel #35
0
        public override void RenderAnnotation(SceneGraph scene, Point renderPoint)
        {
            if (renderPoint.Y < 0)
            {
                return;
            }

            var bubbleSize = this.GetBubbleSize();
            int width = bubbleSize.Width;
            int height = bubbleSize.Height;
            var bubbleRect = new Rectangle(renderPoint.X - width / 2, 0, width, height);
            this.RenderLabel(scene, bubbleRect);
        }
Beispiel #36
0
        private void RenderLabel(SceneGraph scene, Rectangle bubbleRect)
        {
            var label = new Text(bubbleRect, this.Text, this.TextStyle.Clone());
            this.SetTextSetting(label);
            if (bubbleRect.Width <= 0 || bubbleRect.Height <= 0)
            {
                return;
            }
            label.labelStyle.SetNoUpdate(true);
            label.labelStyle.Orientation = TextOrientation.Horizontal;
            label.labelStyle.SetNoUpdate(false);

            scene.Add(label);
        }
        /// <summary>
        /// Create a MoveAction for this node
        /// </summary>
        public void FinalizeMovement()
        {
            if (Node == null) return;

            var mo = new Commands.Undoables.MoveObject(
                OutsideSimulatorApp.GetInstance().SceneRootNode.GetDescendentName(Node),
                StartPos,
                Node.Translation
            );

            mo.Redo();
            OutsideSimulatorApp.GetInstance().CommandStack.Push(mo);

            Node = null;
        }
Beispiel #38
0
 public SceneGraph LoadScene(string fileName, bool normalizeMats = false)
 {
     try
     {
         ComponentPipeline.Instance.SceneProvider.Open(fileName);
         var scene = new SceneGraph();
         ComponentPipeline.Instance.SceneProvider.Build(ref scene, RenderingEngine.NormalizedMats);
         return scene;
     }
     catch (Exception ex)
     {
         Tracer.EntityPrint("Component Pipeline", ConsoleColor.Red, "Scene Loading Error !");
         Tracer.WriteLine(ex.Message);
         Tracer.WriteLine(ex.StackTrace);
         throw;
     }
 }
Beispiel #39
0
 protected internal SceneLightsource(SceneGraph ownr, string name = "DefaultLight")
     : base(name, ownr)
 {
 }
Beispiel #40
0
        public void Build(ref SceneGraph sceneGraph, bool normalizeMats = false)
        {
            if (sceneGraph == null)
            {
                sceneGraph = new SceneGraph();
            }

            sceneGraph.LightOrientation = scn.LightOrientation;

            Tracer.Print("SceneProvider.BuildSceneGraph", "Loading cameras");

            foreach (var camera in scn.Cameras)
            {
                var sceneCamera = sceneGraph.CreateCamera();
                sceneCamera.Position = camera.Position;
                sceneCamera.Direction = camera.Target;
                sceneCamera.Up = camera.Up;
                sceneCamera.Fov = camera.Fov;
            }

            Tracer.Print("SceneProvider.BuildSceneGraph", "Open Obj File");
            var sceneData = OBJLoader.LoadObj(scn.SceneGeo.ObjFilePath);
            sceneData.CalculateBoundingSphere();

            var geoData = sceneGraph.CreateGeometryData(scn.SceneName);
            geoData.BoundingSphereRadius = sceneData.BoundingSphereRadius;
            geoData.BoundingSphereCenter = sceneData.BoundingSphereCenter;
            geoData.Positions = sceneData.Positions.ToList();
            geoData.Normals = sceneData.Normals.ToList();
            geoData.TexCoords = sceneData.Texcoords.ToList();

            Tracer.Print("SceneProvider.BuildSceneGraph", "Creating Materials");

            var matsCache = new Dictionary<string, SceneMaterial>(StringComparer.InvariantCultureIgnoreCase);
            var refCache = new Dictionary<string, SceneResourceReference>(StringComparer.InvariantCultureIgnoreCase);

            foreach (var objMaterialContainer in sceneData.Materials)
            {
                if (string.IsNullOrWhiteSpace(objMaterialContainer.Value.Name))
                    continue;
                var objMat = objMaterialContainer.Value;
                var matRefs = new List<SceneResourceReference>();

                if (!string.IsNullOrWhiteSpace(objMat.DiffuseTexture))
                    EvalTexReference(sceneGraph, objMat.DiffuseTexture, refCache, matRefs);
                if (!string.IsNullOrWhiteSpace(objMat.BumpTexture))
                    EvalTexReference(sceneGraph, objMat.BumpTexture, refCache, matRefs);
                if (!string.IsNullOrWhiteSpace(objMat.AlphaTexture))
                    EvalTexReference(sceneGraph, objMat.AlphaTexture, refCache, matRefs);

                var material = MaterialManager.Create(sceneGraph, objMaterialContainer.Value, normalizeMats);
                material.References.AddRange(matRefs);
                matsCache.Add(material.Name, material);
            }

            Tracer.Print("SceneProvider.BuildSceneGraph", "Loading Geometry");

            foreach (var objGroup in sceneData.Geometry)
            {
                if (objGroup.VIndices.Count == 0)
                    continue;
                var geo = sceneGraph.CreateGeometryEntity(geoData, objGroup.name);
                geo.VertexIndexes = objGroup.VIndices;
                geo.NormalIndexes = objGroup.NIndices;
                geo.TextureIndexes = objGroup.TIndices;

                geo.Material = matsCache[objGroup.mtrl];
            }

            Tracer.Print("SceneProvider.BuildSceneGraph", "Loading Lightsources");
            int index = 0;
            foreach (var lightsource in scn.Lights)
            {
                if (string.IsNullOrWhiteSpace(lightsource.Name))
                {
                    lightsource.Name = lightsource.Type.ToString() + index;
                }
                switch (lightsource.Type)
                {
                    case LightSourceTypes.Point:
                        var pointLight = SceneLightsource.CreatePointLight(lightsource.Name, lightsource.p0);
                        sceneGraph.Add(pointLight);
                        break;
                    case LightSourceTypes.Area:
                        var areaMesh = sceneGraph.Find<SceneMeshEntity>(lightsource.Name);
                        var areaLight = SceneLightsource.CreateAreaLight(lightsource.Name, areaMesh);
                        sceneGraph.Add(areaLight);
                        break;
                    case LightSourceTypes.EnvironmentMap:
                        SceneLightsource envmap = SceneLightsource.CreateInfiniteLight(lightsource.Name, (string) (lightsource["ImagePath"] ?? string.Empty));

                        sceneGraph.Add(envmap);
                        break;
                    case LightSourceTypes.Directional:
                        var dirLight = SceneLightsource.CreateDirectionalLight(lightsource.Name, lightsource.p0);
                        sceneGraph.Add(dirLight);
                        break;
                    case LightSourceTypes.Sphere:
                        throw new NotImplementedException();
                }
                index++;
            }
            Tracer.Print("SceneProvider.BuildSceneGraph", "Complete");
        }
Beispiel #41
0
 private static void EvalTexReference(SceneGraph sceneGraph, string texPath, Dictionary<string, SceneResourceReference> refCache, List<SceneResourceReference> matRefs)
 {
     Guard.NotNullOrEmpty(texPath);
     if (!string.IsNullOrWhiteSpace(texPath) && !refCache.ContainsKey(texPath))
     {
         var texRef = sceneGraph.CreateRef();
         texRef.Value = texPath;
         refCache.Add(texRef.Value, texRef);
         matRefs.Add(texRef);
     }
     else if (refCache.ContainsKey(texPath))
     {
         matRefs.Add(refCache[texPath]);
     }
 }
Beispiel #42
0
 public LightingUniforms(GLProgram program, SceneGraph scene)
     : base(program)
 {
     using (program.Scope ())
     {
         var gl = scene.GlobalLighting;
         if (gl != null)
         {
             globalLighting &= new LightingShaders.GlobalLight ()
             {
                 ambientLightIntensity = gl.AmbientLightIntensity,
                 maxintensity = gl.MaxIntensity,
                 inverseGamma = 1f / gl.GammaCorrection
             };
         }
     }
 }
Beispiel #43
0
 private static void HighlightPolyLine(SceneGraph grpah, Polyline pr)
 {
     // Adjust the values here in order to customize the Highlight.
     pr.HighLightLine = true;
     // Note that the highlight uses the StrokeWidth of the PE so we can temporary change it in order to affect the highlight width.
     var originalStorkeWidth = pr.PE.StrokeWidth;
     pr.PE.StrokeWidth = 4;
     pr.Highlight(grpah, Color.Gray, Color.Gray);
     pr.PE.StrokeWidth = originalStorkeWidth;
 }
Beispiel #44
0
 public abstract void SetupScene(SceneGraph scene);
Beispiel #45
0
        private int BuildNodeRecursive(ref SceneGraph parent, List<J3DFormat.HierarchyData> nodeList, int listIndex)
        {
            for (int i = listIndex; i < nodeList.Count; ++i)
            {
                J3DFormat.HierarchyData node = nodeList[i];
                SceneGraph newNode;

                switch (node.Type)
                {
                    //If it's a new node, push down in the stack one.
                    case J3DFormat.HierarchyDataTypes.NewNode:
                        newNode = new SceneGraph(node.Type, node.Index);
                        i += BuildNodeRecursive(ref newNode, nodeList, i + 1);
                        parent.Children.Add(newNode);
                        break;

                    //If it's the end node, we need to go up.
                    case J3DFormat.HierarchyDataTypes.EndNode:
                        return i - listIndex + 1;

                    //If it's a material, joint, or shape, just produce them.
                    case J3DFormat.HierarchyDataTypes.Material:
                    case J3DFormat.HierarchyDataTypes.Joint:
                    case J3DFormat.HierarchyDataTypes.Batch:
                    case J3DFormat.HierarchyDataTypes.Finish:
                        break;
                    default:
                        Console.WriteLine("You broke something.");
                        break;
                }

                //Update what we're about to add, because NewNodes can change it.
                node = nodeList[i];
                parent.Children.Add(new SceneGraph(node.Type, node.Index));
            }

            return 0;
        }
Beispiel #46
0
        public override void SetupScene(SceneGraph scene)
        {
            Tracer.Print("SceneSetup", "Start building scene data");

            builder.Build(scene);

            Tracer.Print("SceneSetup", "Creating buffers");

            var optixContext = ComponentPipeline.Instance.Session.OptixContext;
            ComponentPipeline.Instance.Session.Frame.CurrentCamera = builder.Camera;

            var spdBuffDesc = new BufferDesc
            {
                Width = outputBuffer.Width + 1,
                Height = outputBuffer.Height + 1,
                Depth = outputBuffer.Depth,
                Format = Format.Float3,
                Type = BufferType.InputOutput
            };
            hdrBuffer = new Buffer(optixContext, spdBuffDesc);

            hdrBuffer.SetData(new Vector3[spdBuffDesc.Width * spdBuffDesc.Height]);

            var rndBuffDesc = new BufferDesc
            {
                Width = outputBuffer.Width + 1,
                Height = outputBuffer.Height + 1,
                Depth = outputBuffer.Depth,
                Format = Format.UInt,
                Type = BufferType.InputOutput
            };
            rndBuffer = new Buffer(optixContext, rndBuffDesc);
            GenerateSeeds();
            optixContext["rnd_seeds"].Set(rndBuffer);
            optixContext["hdr_buffer"].Set(hdrBuffer);

            optixContext["top_object"].Set(ComponentPipeline.Instance.Session.Frame.TopObject);
            optixContext["output_buffer"].Set(outputBuffer);
            optixContext["scene_epsilon"].Set(0.00001f);
            optixContext["rr_begin_depth"].Set(rrBeginDepth);
            optixContext["max_depth"].Set(maxDepth);
            optixContext["sqrt_num_samples"].Set(sqrtSamples);
            optixContext["bad_color"].SetFloat3(new Vector3(1.0f, 0.0f, 0.0f));
            //optixContext["bg_color"].Set(100 / 255.0f, 149 / 255.0f, 237 / 255.0f);
            optixContext["bg_color"].Set(0f,0f,0f);

            optixContext["lights"].Set(ComponentPipeline.Instance.Session.Frame.LightBuffer);
            optixContext["lightTriangles"].Set(ComponentPipeline.Instance.Session.Frame.LightTrianglesBuffer);

            optixContext["Y_log_av"].Set(yAvg);
            optixContext["Y_max"].Set(yMax);
            optixContext["gamma_value"].Set(gamma_value);

            QMC.InitContext(optixContext);
            Tracer.Print("SceneSetup", "Optix context compilation.");

            ComponentPipeline.Instance.Session.OptixContext.Compile();
            ComponentPipeline.Instance.Session.OptixContext.BuildAccelTree();

            Tracer.Print("SceneSetup", "Finished.");
        }
 protected internal SceneResourceReference(SceneGraph ownr)
     : base(string.Empty, ownr)
 {
 }
 public override void Highlight(SceneGraph scene, Color outlineColor, Color fillColor)
 {
     base.Highlight(scene, outlineColor, fillColor);
 }
Beispiel #49
0
 protected internal SceneMeshData(SceneGraph ownr, string name)
     : base(name, ownr)
 {
 }
Beispiel #50
0
        private void WalkModelJointRecursive(ref Matrix4[] jointMatrix, ref Matrix4 jointParent, SceneGraph curNode, int sceneDepth)
        {
            switch (curNode.NodeType)
            {
                case J3DFormat.HierarchyDataTypes.Joint:
                    var joint = _file.Joints.GetJoint(curNode.DataIndex);
                    string jointName = _file.Joints.GetString(
                        _file.Joints.GetStringTableEntry(_file.Joints.GetStringIndex(curNode.DataIndex)));

                    Vector3 jointRot = joint.GetRotation().ToDegrees();
                    Vector3 translation = joint.GetTranslation();
                    Matrix4 tranMatrix = Matrix4.CreateTranslation(translation);
                    Matrix4 rotMatrix = Matrix4.CreateRotationX(jointRot.X) * Matrix4.CreateRotationY(jointRot.Y) * Matrix4.CreateRotationZ(jointRot.Z);
                    Matrix4 scaleMatrix = Matrix4.CreateScale(joint.GetScale());
                    Matrix4 modelMatrix = tranMatrix * rotMatrix * scaleMatrix;


                    jointMatrix[curNode.DataIndex] = modelMatrix * jointParent;
                    Vector3 finalJointTranslation = jointMatrix[curNode.DataIndex].ExtractTranslation();
                    Vector3 parentJointTrans = (Vector3.TransformPosition(Vector3.Zero, jointParent));
                    DebugRenderer.DrawLine(finalJointTranslation, parentJointTrans, Color.White);

                    jointParent = jointMatrix[curNode.DataIndex];
                    Console.WriteLine("Joint {0} at depth: {1}", jointName, sceneDepth);
                    break;

                case J3DFormat.HierarchyDataTypes.NewNode:
                    sceneDepth++;
                    break;
            }

            foreach (SceneGraph subNode in curNode.Children)
            {
                WalkModelJointRecursive(ref jointMatrix, ref jointParent, subNode, sceneDepth);
            }
        }
Beispiel #51
0
        private void DrawModelRecursive(ref Matrix4[] jointMatrix, SceneGraph curNode, BaseRenderer renderer, bool bSelectedPass)
        {
            switch (curNode.NodeType)
            {
                case J3DFormat.HierarchyDataTypes.Material:
                    if (!bSelectedPass)
                        GL.BindTexture(TextureTarget.Texture2D, GetGLTexIdFromCache(curNode.DataIndex));
                    break;

                case J3DFormat.HierarchyDataTypes.Batch:
                    /* For each batch, we're going to enable the
                         * appropriate Vertex Attributes for that batch
                         * and set default values for vertex attribs that
                         * the batch doesn't use, then draw all primitives
                         * within it.*/

                    if (bSelectedPass)
                    {
                        #region Selected
                        float[] front_face_wireframe_color = { 1.0f, 1.0f, 1.0f, 1.0f };
                        float[] back_face_wireframe_color = { 0.7f, 0.7f, 0.7f, 0.7f };

                        GL.LineWidth(1);
                        GL.Enable(EnableCap.CullFace);
                        //GL.Disable(EnableCap.DepthTest);
                        GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
                        GL.EnableVertexAttribArray((int)BaseRenderer.ShaderAttributeIds.Position);

                        // 1. Draw the back-faces with a darker color:
                        GL.CullFace(CullFaceMode.Back);
                        GL.VertexAttrib4((int)BaseRenderer.ShaderAttributeIds.Color, back_face_wireframe_color);
                        foreach (var packet in _renderList[curNode.DataIndex].Packets)
                        {
                            int vertexIndex = 0;
                            foreach (var primitive in packet.PrimList)
                            {
                                //Uhh... 
                                ushort drawIndex = packet.DrawIndexes[primitive.PosMatrixIndex[vertexIndex] / 3];
                                bool isWeighted = _file.Draw.IsWeighted(drawIndex);

                                if (isWeighted)
                                {

                                }
                                else
                                {
                                    var jnt = _file.Joints.GetJoint(curNode.DataIndex);
                                    Vector3 jntRot = jnt.GetRotation().ToDegrees();
                                    Vector3 trans = jnt.GetTranslation();
                                    Matrix4 trnMatrix = Matrix4.CreateTranslation(trans);
                                    Matrix4 rtMatrix = Matrix4.CreateRotationX(jntRot.X) * Matrix4.CreateRotationY(jntRot.Y) *
                                                        Matrix4.CreateRotationZ(jntRot.Z);
                                    Matrix4 sclMatrix = Matrix4.CreateScale(jnt.GetScale());

                                    Matrix4 final = trnMatrix * rtMatrix * sclMatrix;

                                    //renderer.SetModelMatrix(Matrix4.Identity);
                                    renderer.SetModelMatrix(final);
                                }

                                GL.DrawArrays(primitive.DrawType, primitive.VertexStart, primitive.VertexCount);

                                vertexIndex++;
                            }

                        }


                        // 2. Draw the front-faces with a lighter color:
                        GL.CullFace(CullFaceMode.Front);
                        GL.VertexAttrib4((int)BaseRenderer.ShaderAttributeIds.Color, front_face_wireframe_color);
                        /*foreach (var primitive in _renderList[curNode.DataIndex])
                        {
                            GL.DrawArrays(primitive.DrawType, primitive.VertexStart, primitive.VertexCount);
                        }*/

                        GL.DisableVertexAttribArray((int)BaseRenderer.ShaderAttributeIds.Position);
                        GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);
                        //GL.Enable(EnableCap.DepthTest);
                        GL.LineWidth(1);
                        #endregion
                    }
                    else
                    {
                        SetVertexAttribArraysForBatch(true, curNode.DataIndex);
                        //GL.CullFace(CullFaceMode.Front);
                        for (int packetIndex = 0; packetIndex < _renderList[curNode.DataIndex].Packets.Count; packetIndex++)
                        {
                            RenderPacket packet = _renderList[curNode.DataIndex].Packets[packetIndex];
                            foreach (var primitive in packet.PrimList)
                            {
                                renderer.SetModelMatrix(Matrix4.Identity);

                                if (primitive.PosMatrixIndex.Count > 0)
                                {
                                    var transformedData = new J3DRenderer.VertexFormatLayout[primitive.VertexCount];

                                    //For each vertex within this primitive, we're going to get its id.
                                    for (int vertexIndex = 0; vertexIndex < primitive.VertexCount; vertexIndex++)
                                    {
                                        ushort vertIndex = primitive.PosMatrixIndex[vertexIndex];
                                        ushort drawIndex = packet.DrawIndexes[vertIndex / 3];

                                        //ehh
                                        int seriously = 0;
                                        while (drawIndex == 0xFFFF)
                                        {
                                            RenderPacket prevPacket =
                                                _renderList[curNode.DataIndex].Packets[packetIndex - seriously];
                                            drawIndex = prevPacket.DrawIndexes[vertIndex / 3];
                                            seriously++;
                                        }

                                        bool isWeighted = _file.Draw.IsWeighted(drawIndex);
                                        if (isWeighted)
                                        {
                                            ushort numBonesAffecting =
                                                _file.Envelopes.GetCount(_file.Draw.GetIndex(drawIndex));

                                            //Much WTFs
                                            ushort offset = 0;
                                            for (ushort i = 0; i < _file.Draw.GetIndex(drawIndex); i++)
                                                offset += _file.Envelopes.GetCount(i);

                                            offset *= 2;
                                            Matrix4 finalTransform = Matrix4.Identity;
                                            for (ushort i = 0; i < numBonesAffecting; i++)
                                            {
                                                ushort boneIndex =
                                                    _file.Envelopes.GetIndexOffset((ushort)(offset + (i * 0x2)));
                                                float boneWeight = _file.Envelopes.GetWeight((ushort)((offset / 2) + i));

                                                Matrix3x4 envMatrix = _file.Envelopes.GetMatrix(boneIndex);
                                                Matrix4 newEnvelopeMtx = new Matrix4(envMatrix.Row0, envMatrix.Row1,
                                                    envMatrix.Row2, new Vector4(0, 0, 0, 1));

                                                SkeletonJoint joint = _skeleCopy[boneIndex];
                                                //Matrix4 transMatrix = Matrix4.CreateTranslation(joint.Position);
                                                //We need to use the bone's matrix from EVP1 to get the joint matrix
                                                Matrix4 jointMtx = joint.Rotation * newEnvelopeMtx;

                                                //finalTransform = Matrix4.Mult(jointMtx * newEnvelopeMtx, boneWeight) * finalTransform;
                                                //ToDo: This is the wrong scale.
                                                //AddScaleMatrix(ref finalTransform, Matrix4.Mult(jointMtx, newEnvelopeMtx), 1f);
                                            }

                                            transformedData[vertexIndex] = _vertDataBind[primitive.VertexStart + vertexIndex];

                                            Vector3 vertPosition = transformedData[vertexIndex].Position;
                                            transformedData[vertexIndex].Position = Vector3.TransformPosition(vertPosition, finalTransform);
                                        }
                                        else
                                        {
                                            //If the vertex is not weighted, we're just going to use the position
                                            //from the bone matrix. Something like this.
                                            Vector3 vertPosition =
                                                _vertDataBind[primitive.VertexStart + vertexIndex].Position;

                                            transformedData[vertexIndex] = _vertDataBind[primitive.VertexStart + vertexIndex];

                                            SkeletonJoint joint = _skeleCopy[_file.Draw.GetIndex(drawIndex)];
                                            Matrix4 transMatrix = Matrix4.CreateTranslation(joint.Position);
                                            Matrix4 final = joint.Rotation * transMatrix;
                                            transformedData[vertexIndex].Position = Vector3.TransformPosition(vertPosition, final);
                                        }
                                    }

                                    //Re-upload the subsection to the buffer.
                                    GL.BindBuffer(BufferTarget.ArrayBuffer, _glVbo);
                                    GL.BufferSubData(BufferTarget.ArrayBuffer, (IntPtr)(primitive.VertexStart * (9 * 4)),
                                        (IntPtr)(primitive.VertexCount * (9 * 4)), transformedData);

                                    float[] front_face_wireframe_color = { 1.0f, 1.0f, 1.0f, 1.0f };
                                    GL.VertexAttrib4((int)BaseRenderer.ShaderAttributeIds.Color, front_face_wireframe_color);
                                }


                                GL.DrawArrays(primitive.DrawType, primitive.VertexStart, primitive.VertexCount);
                            }

                        }

                        SetVertexAttribArraysForBatch(false, curNode.DataIndex);
                    }

                    break;
            }

            foreach (SceneGraph subNode in curNode.Children)
            {
                DrawModelRecursive(ref jointMatrix, subNode, renderer, bSelectedPass);
            }
        }
 public void SetNode(SceneGraph Node)
 {
     this.Node = Node;
     StartPos = Node.Translation;
 }
Beispiel #53
0
 protected internal SceneMaterial(SceneGraph ownr, string name = "DefaultMaterial")
     : base(name, ownr)
 {
     References = new List<SceneResourceReference>();
 }
Beispiel #54
0
        public void Build(SceneGraph scene)
        {
            BuildCache = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase);
            var camera = scene.First<SceneCamera>();
            Guard.NotNull(camera, "Couldn't find camera in scene");

            var cameras = scene.OfType<SceneCamera>().ToArray();
            Cameras = new Camera[cameras.Length];
            for (int i = 0; i < cameras.Length; i++)
            {
                Cameras[i] = new Camera();
                Cameras[i].LookAt(cameras[i].Position, cameras[i].Direction, cameras[i].Up);
                Cameras[i].Fov = camera.Fov;
                Cameras[i].BuildView();
            }

            var sceneGeometryData = scene.First<SceneMeshData>();
            Guard.NotNull(sceneGeometryData, "Couldn't find sceneGeometryData in scene");
            var sceneGeometry = scene.Subset<SceneMeshEntity>().ToArray();
            Guard.NotNullOrEmpty(sceneGeometry, "No scene geometry present");
            var sceneMaterials = scene.Subset<SceneMaterial>().ToArray();
            Guard.NotNullOrEmpty(sceneMaterials, "No scene materials present");
            var sceneLights = scene.Subset<SceneLightsource>().ToArray();
            Guard.NotNullOrEmpty(sceneLights, "No scene lightsources present");
            var sceneResources = scene.Subset<SceneResourceReference>().ToArray();
            Camera = new Camera();
            Camera.LookAt(camera.Position, camera.Direction, camera.Up);
            Camera.Fov = camera.Fov;
            Camera.BuildView();

            Tracer.WriteLine("Start Building Materials");
            this.BuildMaterials(sceneMaterials, sceneResources);

            BuildCache.Add("Materials", sceneMaterials);

            Tracer.WriteLine("Start Building Geometry");
            var areaLights = sceneLights.Where(lt => lt.LightType == LightSourceTypes.Area).ToArray();

            if (areaLights.Any())
            {
                BuildCache.Add("AreaLights", areaLights.ToArray());
            }

            this.BuildGeometry(sceneGeometryData, sceneGeometry, areaLights.Any(), areaLights);
            this.BoundingSphereRadius = sceneGeometryData.BoundingSphereRadius;
            BuildCache.Add("Geometry", sceneGeometry);

            Tracer.WriteLine("Start Building Lightsources");
            this.BuildLights(sceneLights);

            Session.Frame.TopObject = this.topObject;
        }
Beispiel #55
0
        private SceneGraph BuildSceneGraphFromInfo()
        {
            SceneGraph root = new SceneGraph();
            var hierarchyData = _file.Info.GetHierarchyData();

            BuildNodeRecursive(ref root, hierarchyData, 0);

            return root;
        }
Beispiel #56
0
 public RaycastBoundObject(SceneGraph.OTBoundingShape bb, EngineCollisionMesh _RCCM)
 {
     boundingShape = bb;
     RCCM = _RCCM != null ? _RCCM : bb.cm;
 }
Beispiel #57
0
 protected internal SceneCamera(SceneGraph ownr, string name = "DefaultCamera")
     : base(name, ownr)
 {
 }