How to share a struct between C++/DirectX and HLSL?
Asked Answered
F

1

6

I'm in the process of learning C++ and DirectX, and I'm noticing a lot of duplication in trying to keep structs in my HLSL shaders and C++ code in sync. I'd like to share the structs, since both languages have the same #include semantics and header file structure. I met success with

// ColorStructs.h
#pragma once

#ifdef __cplusplus

#include <DirectXMath.h>
using namespace DirectX;

using float4 = XMFLOAT4;

namespace ColorShader
{

#endif

    struct VertexInput
    {
        float4 Position;
        float4 Color;
    };

    struct PixelInput
    {
        float4 Position;
        float4 Color;
    };

#ifdef __cplusplus
}
#endif

The problem, though, is during the compilation of these shaders, FXC tells me input parameter 'input' missing sematics on the main function of my Pixel shader:

#include "ColorStructs.h"

void main(PixelInput input)
{
    // Contents elided
}

I know that I need to have the semantics like float4 Position : POSITION but I can't come up with a way to do this that wouldn't violate C++'s syntax.

Is there a way I can keep the structs common between HLSL and C++? Or is it unfeasible, and requires duplicating the structs between the two source trees?

Fictive answered 19/1, 2016 at 20:37 Comment(2)
Note that it's generally considered a bad idea to put "using namespace" in an unrelated header file (since it makes accidental name collisions more likely).Octal
That's a good point! This started out as a C++ header, and I forgot to remove it. Thanks for pointing that out!Fictive
D
6

You could use a function macro to remove the semantic specifiers while compiling C++

#ifdef __cplusplus
#define SEMANTIC(sem) 
#else
#define SEMANTIC(sem) : sem
#endif

struct VertexInput
{
    float4 Position SEMANTIC(POSITION0);
    float4 Color SEMANTIC(COLOR0);
};
Divvy answered 19/1, 2016 at 21:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.