Zototh

DX11 Instance Shader Problem

Recommended Posts

Zototh    1

I am using slimDX and am having a problem with a shader. I have an instance Shader that works perfect but I needed one for drawing fonts manually. The idea is to create the plane and simple instance it with separate position color and texture coordinates for each char.  I know this post is terribly long but any help would be appreciated. I tried to provide everything needed but if you need more I will be glad to post it.

This is the shader. the only difference between it and the working one is the instance texture coordinates. I was able to render 4,000 spheres with 30,000 faces with the original and still maintain a 100+ framerate. I don't know if that is a lot but it looked like it to me.

cbuffer cbVSPerFrame:register(b0)
{
	row_major matrix world;
	row_major matrix viewProj;
};

Texture2D g_Tex;
SamplerState g_Sampler;

struct VSInstance
{
	float4 Pos : POSITION;
	float3 Normal : NORMAL;
	float2 Texcoord : TEXCOORD0;

	float4 model_matrix0 : TEXCOORD1;

	float4 model_matrix1 : TEXCOORD2;

	float4 model_matrix2 : TEXCOORD3;

	float4 model_matrix3 : TEXCOORD4;
  // this is the only addition
	float2 instanceCoord:TEXCOORD5;
	float4 Color:COLOR;
};
struct PSInput
{
	float4 Pos : SV_Position;
	float3 Normal : NORMAL;
	float4 Color:COLOR;
	float2 Texcoord : TEXCOORD0;
};


PSInput Instancing(VSInstance In)
{
	PSInput Out;
	// construct the model matrix

	row_major float4x4 modelMatrix =
	{
		In.model_matrix0,
		In.model_matrix1,
		In.model_matrix2,
		In.model_matrix3
	};
  
	Out.Normal = mul(In.Normal, (row_major float3x3)modelMatrix);
	float4 WorldPos = mul(In.Pos, modelMatrix);

	Out.Pos = mul(WorldPos, viewProj);
	Out.Texcoord = In.instanceCoord;
	Out.Color = In.Color;
	return Out;
}

float4 PS(PSInput In) : SV_Target
{
	return g_Tex.Sample(g_Sampler, In.Texcoord);
}

technique11 HWInstancing
{
	pass P0
	{
		SetGeometryShader(0);
		SetVertexShader(CompileShader(vs_4_0, Instancing()));
		SetPixelShader(CompileShader(ps_4_0, PS()));
	}
}

this is the input elements for the 2 buffers

        private static readonly InputElement[] TextInstance = {
            new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
            new InputElement("NORMAL", 0, Format.R32G32B32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0),
            new InputElement("TEXCOORD", 0, Format.R32G32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0),
            new InputElement("TEXCOORD", 1, Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1 ),
            new InputElement("TEXCOORD", 2, Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1 ),
            new InputElement("TEXCOORD", 3, Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1 ),
            new InputElement("TEXCOORD", 4, Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1 ),
            new InputElement("TEXCOORD", 5, Format.R32G32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1 ),
            new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1 )
        };

the struct for holding instance data. 

    [StructLayout(LayoutKind.Sequential)]
    public struct InstancedText
    {
        public Matrix InstancePosition;
        public Vector2 InstanceCoords;
        public Color4 Color;
    };

instanceData buffer creation. Instance Positions is a simple List<InstancedText> above

            DataStream ds = new DataStream(InstancePositions.ToArray(), true, true);
            
            BufferDescription vbDesc = new BufferDescription();
            vbDesc.BindFlags = BindFlags.VertexBuffer;
            vbDesc.CpuAccessFlags = CpuAccessFlags.None;
            vbDesc.OptionFlags = ResourceOptionFlags.None;
            vbDesc.Usage = ResourceUsage.Default;
            vbDesc.SizeInBytes = InstancePositions.Count * Marshal.SizeOf<InstancedText>();
            vbDesc.StructureByteStride = Marshal.SizeOf<InstancedText>();
            ds.Position = 0;

            instanceData = new Buffer(renderer.Device, vbDesc);

 

and finally the render code.

the mesh is a model class that contains the plane's data. PositionNormalTexture is just a struct for those elements.

            renderer.Context.InputAssembler.InputLayout = new InputLayout(renderer.Device,
                effect.GetTechniqueByName("HWInstancing").GetPassByIndex(0).Description.Signature, TextInstance);
            renderer.Context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            renderer.Context.InputAssembler.SetVertexBuffers(0, new 
               VertexBufferBinding(mesh.VertexBuffer, Marshal.SizeOf<PositionNormalTexture>(), 0));
            renderer.Context.InputAssembler.SetIndexBuffer(mesh.IndexBuffer, SlimDX.DXGI.Format.R32_UInt, 0);
            renderer.Context.InputAssembler.SetVertexBuffers(1, new VertexBufferBinding(instanceData,
                 Marshal.SizeOf<InstancedText>(), 0));

            effect.GetVariableByName("g_Tex").AsResource().SetResource(textures[fonts[name].Name]);

            EffectTechnique currentTechnique = effect.GetTechniqueByName("HWInstancing");
            for (int pass = 0; pass < currentTechnique.Description.PassCount; ++pass)
            {
                EffectPass Pass = currentTechnique.GetPassByIndex(pass);
                System.Diagnostics.Debug.Assert(Pass.IsValid, "Invalid EffectPass");
                Pass.Apply(renderer.Context);
                renderer.Context.DrawIndexedInstanced(mesh.IndexCount, InstancePositions.Count, 0, 0, 0);
            };

I have been over everything I can think of to find the problem but I can't seem to locate it.

my best guess is the instance data buffer is wrong somehow since VS graphics debugger shows no output from vertex shader stage

 but I just can't see where.

Edited by Zototh

Share this post


Link to post
Share on other sites
Zototh    1

wow it just hit me what I missed.

instanceData = new Buffer(renderer.Device, vbDesc); <---- should be instanceData = new Buffer(renderer.Device, ds, vbDesc);

LOL what a dumb mistake and spent 2 days trying to find it.

edit: seems I forgot to do a scaling matrix also when I created the positions but the shader works perfect

Edited by Zototh

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Similar Content

    • By John Lamontagne
      About the Game
      Lore Summary
      Coming Soon!
      The Jist
      Ruinic is a competitive multiplayer dungeon crawler -- CMDC for short. The objective of the game is to farm loot, hone your skills, discover ancient and forgotten secrets, and compete with other players via a comprehensive ranking system. In addition to this, Ruinic will feature a strong social element, as guilds will also be able to compete with each other.
      Gear and skills
      Unlike most other dungeon crawlers and RPGs, your character will not be locked to any one class; rather, your characters skill will be determined through a combination of how much time they've put into utilizing that particular skill and the abilities of the gear they're using. The skills in Ruinic will be centered around four different types of game play: Damage, Tanking, Healing, and Necromancy. All of these game play types will have to work in harmony in order for the players to survive the harsh environments in which they find themselves. Players may also create unique gear builds in order to hybrid between these roles and secure all the treasures of their adventures for themselves. The first three types of game play are pretty standard in most games, but the fourth is unique to Ruinic. More about these skills can be found below.

      Damage - As should be obvious, the purpose of damage builds is to unleash as much destruction upon foes as possible. It is vital that enough damage is done in order to assure that the Tank is not overwhelmed and that the Necromancer is able to fulfill its role. Tank The purpose of the tank is to concentrate the wrath of enemies upon itself and soak up as much of their damage as possible. Healer The purpose of the healer is to, as simply put as possible, ensure that everyone stays alive Necromancer The Necromancer plays an extremely important role. The purpose of Necromancy is to harvest the life force of dead foes and channel it into forms of energy usable by other roles. Without the Necromancer, the Tank, Damage, and Healing roles cannot effectively perform their jobs. The Necromancer plays an extremely important role. The purpose of Necromancy is to harvest the life force of dead foes and channel it into forms of energy usable by other roles. Without the Necromancer, the Tank, Damage, and Healing roles cannot effectively perform their jobs.

      Dungeons
      Dungeons, which will make up the majority of content within the world of Ruinic will be massive, sprawling labyrinths filled to the brim with monsters, traps, puzzles, and other players. Entrances to these dungeons will appear to the overworld occasionally, so players should always be on their toes to be the first ones to jump in, explore, and amass untold riches. After a set amount of time has passed, dungeons will begin to become unstable and collapse in on themselves. Players should then quickly evacuate, as a stray piece of ceiling, fire storm, or chasm in the ground could see that much of their acquired treasure is lost. 
      PVP
      Player-versus-player interactions in Ruinic will be very similar to older hardcore ORPGs such as Tibia, where player killing can be extremely rewarding, but potentially disastrous should you decide to take a risk and slay your fellow explorers. Past a particular introductory level, which is yet to be determined, the initiation of a PVP battle will be unrestricted aside for some severe penalties for the initiating player. If you are successful in slaying your opponent, you will receive the treasures they have acquired in their backpack as well as some of the experience they gained while in the dungeon, but, if you are unsuccessful, there are some rather nasty consequences! Upon attacking another player in a dungeon, you will receive a red skull, which will last for a duration of time scalable to the difference between your level and the victims. This could range anywhere from 30 minutes for a player who is equal to or greater than your level, to an hour for players who are of a much lower level. If you die while skulled, you will not only lose all of the acquired items within your backpack, but also your equipped gear and the experience acquired from the dungeon you were skulled in, as well as every dungeon you visited after you received your skull. If you attempt to enter a hub city while still skulled, not only will you have guards to fend off who will have been warned of your treachery, but players will also be able to attack you without penalty, so it's best to wait out the heat before trying to resurface! 
      Hub Citites
      The hub cities are where players will congregate to interact, buy and sell their amassed loot, host clan events, and participate in various other social activities. Players will be able to set up their own custom stocked shops, where you can set your own prices and allow other players to swing by and see what you have up for grabs. More information will be released about hub cities as we move forward in development, but expect an update about the first city, Thelara, to be released very soon!
      Website & Community
      You can read more about the game and sign up for early access at our website, here:
      http://www.ruinic.com/community

      Screenshots and Details
      Below you may find a collection of updates that I will also post as replies in this thread.
      9/14/2017

      9/9/2017

      8/28/2017

      2/7/2016



      2/12/2016

      2/22/2016

    • By Affgoo
      About us:
      We are a team of 14 developers developing multiple mid scope games both are over halfway complete. We polish all of our games and focus on quality.


      We are a small team, everyone currently on the team and future teammates must be interested in game development as a whole and not just one role, being a small indie company it is very important that you can wear a few hats and not just one. Everyone on our team is a game dev.

      looking for:
      3d Artist (hand painting a huge plus)
      3d Animator
      entry level Software engineer with reasonable skills in c# / shaders. 

      ^ requirement for all positions: A true love of game development and to be very self motivated.
      We are a very active team, you must be too. 


      If interested or for more information add me on skype: nicholas.boucher4


      Atlas Sentry art style: (art complete)(code complete)
      http://www.slidedb.com/games/atlas-sentry

      Rat n Gat art style: In Devlopment

    • By FunInfusedGames
      Description:
      Platinum Kill is a fast paced, run and gun shooter featuring lots of action, weapons, and a tongue in cheek sense of humor. It will feature six unique levels each with a challenging level end boss. The game features a chiptune soundtrack with a unique song for each level. The graphics will be a low res pixel art style. The game is playable with 1 to 5 player local co-op (4 gamepads and 1 keyboard player) and up to 4 AI players (limited to 5 real and AI players total).
      This game also features AI helpers that are unlocked when you reach kill streak milestones. These helpers are slightly intelligent characters that you play alongside you, giving you the illusion of playing with friends even if you're all alone. They stay with you until they die or your player is killed.
      Interested in feedback and anyone willing to playtest.
       

      The obvious comparison with Platinum Kill is going to be with Contra. Contra certainly is a big influence on this game (the original two NES titles mainly) but it is my hope that Platinum Kill can do enough different and better that it can stand on its own as not a copy but rather an envolution of the genre. There have been other entries in the genre since Contra and Super C, but I feel like those failed to really capture the excitement and pace of the original games. I want to recapture that as my starting point and layer improvements upon it. Think how the new Doom still feels like the original Doom games but then expands upon it.

      The original game this started as (see History section below) took about a month and a half to complete and I've been working on this version since January of 2017. I'm hoping I can complete this in the next 3 months but I'm bad at estimates and it'll probably end up taking way longer. I do all the programming and design myself and UI graphics and then contract out for in-game graphics and music.
      I want to talk about my game here, share what I am doing and gather feedback on how I can make the game better. If you want to playtest my game yourself and can use Steam on Windows, just drop me a line.

      Screenshots:
      http://www.funinfused.com/images/PK_SlimeMonster.png
      http://www.funinfused.com/images/PK01.jpg
      http://www.funinfused.com/images/PK02.jpg
      http://www.funinfused.com/images/PK04.png
      http://www.funinfused.com/images/PKBoss1Emoji.gif

      Videos (newest to oldest):
      https://www.youtube.com/watch?v=a1AYpxt4EC4
      https://www.youtube.com/watch?v=3OCgf9eaQgg
      https://www.youtube.com/watch?v=vtfCtKpu-l0
      https://www.youtube.com/watch?v=uXrLNczWMdQ
      https://www.youtube.com/watch?v=yzRybGbitH8
      https://www.youtube.com/watch?v=NyVwYudnXNw
      https://www.youtube.com/watch?v=Xl3fykqJ1c4&t=2s
      Engine:
      Custom built using C# and MonoGame.

      Platform:
      Steam (Windows). Maybe PS4 down the road.

      Game History:
      Platinum Kill started off as Ultra Aktion for XBLIG and later ported to itch.io. My hope was that I could do monthly releases of titles and be able to support myself as a full time indie dev. Because of the short timeframe, I did all the graphics using simple colored rectangles and instead focused on making the gameplay as fun as possible. To this end, I think I succeeded well, but in a flooded marketplace and even at just a dollar, Ultra Aktion didn't stand out. XBLIG, where I released it initially, was also near the end and had a plethorea of issues (such as the game showing up in new releases but not being able to be downloaded for over a week before Microsoft finally fixed the issue). After the itcho.io release, I placed Ultra Aktion in Steam Greenlight was the comment that if it got appproved, I'd turn it into a full proper game. Well it did and that's what I'm doing now.
      https://www.youtube.com/watch?v=9LAI7DURjaU

      Dev History:
      I'm the developer and founder of Fun Infused Games. My focus has always been on creating 2D old school styled games, games that I grew up playing and have a special place in my heart for. I started making games back in 2009 with XNA and released 8-9 games for Xbox Live Indie Games (XBLIG) over the next few years. After XBLIG folded, I tried a few other platforms, releasing one game on iOS (Hypership Out of Control) and two on Ouya (ugh, waste of time). For the past few years I have been doing Steam releases and have released improved versions of four of my XBLIG titles on the platform. I also have a PS4 dev kit and a mostly working version of one of my games, but I have since gotten distracted doing Steam games. One day I plan to get back to PS4 stuff and release an actual game there too.

      Links:
      Website - http://www.funinfused.com
      Twitter - https://twitter.com/funinfused
      YouTube - https://www.youtube.com/channel/UCtzFZwb1UhLKp8edddZbq8g
      Facebook - http://www.facebook.com/pages/Fun-Infused-Games/261073264705
      SoundCloud - https://soundcloud.com/user1903103
      Ultra Aktion on itcho.io - https://funinfusedgames.itch.io/ultra-aktion
      Current Steam Releases - http://store.steampowered.com/search/?developer=Fun Infused Games
    • By EvaBalikova
      Main menu in Feudal Alloy. 
      twitter
    • By BG109
      Hi guys!
      I would really appreciate some feedback and advice from you guys on the game I'm developing
      The game I'm working on is a 2D ARPG single/multiplayer using my own custom engine which is a 2D OpenGL engine inC++.
      The game have two distinct areas: outdoor world environments and dungeons. Right now I have reached a point where I'm starting to feel quite satisfied with the outdoor environments but the dungeons feel very lacking right now. Whereas the outdoor environments have at-least somewhat of a depth feeling to them the dungeons just feel... flat...
      I am not sure how to improve the graphics in the dungeon areas to get a bit more depth and/or vivid feeling. Outdoor was easier as I could play a bit with sun-shadows and parallaxing but I cant quite use that in the dungeons which is causing problems.
      I have posted a few images below on both the outdoor world and the dungeons for comparison as well as a small update trailer if you want to just get a feeling for the current dynamics of the game. Any feedback or ideas on how to improve upon the dungeons would be greatly appreciated. This is the first real game I have developed so I'm sure you guys have a lot of ideas I haven't really though about yet
       
      Best Regards BG109




       
      Trailer/Update Video:
      https://www.youtube.com/watch?v=aZthsgv1zPg
  • Popular Now