Three.js 中非常简单的自定义着色器 - 如何使其工作?

发布于 2024-12-27 07:31:22 字数 1161 浏览 1 评论 0原文

我正在尝试为 Three.js 制作最简单的自定义着色器,但我还没有弄清楚如何使其工作。我使用着色器的对象根本不出现。

在我的页面 html 中,我有:

<script id="simplefs" type="x-shader/x-fragment">

    void main(void) {
        gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
    }
</script>

<script id="simplevs" type="x-shader/x-vertex">

    void main(void) {
        gl_Position = modelViewMatrix * projectionMatrix * vec4(position, 1.0);
    }
</script>

然后在 javascript 中:

var vertShader = document.getElementById("simplevs").innerHTML;
var fragShader = document.getElementById("simplefs").innerHTML;

var myMaterial = new THREE.ShaderMaterial({
    vertexShader : vertShader,
    fragmentShader: fragShader
});

var baseBevel = new THREE.Mesh(new THREE.CylinderGeometry(BaseRadius - BaseBevel, BaseRadius, BaseBevel, 100, 100, false),
                               myMaterial )
baseBevel.position.x = x;
baseBevel.position.y = y;
baseBevel.position.z = BaseHeight - (BaseBevel / 2.0);
baseBevel.rotation.x = Math.PI / 2.0;

scene.add(baseBevel); 

对象应该在的地方,什么也没有。如果我用 MeshLambertMaterial 替换材质,效果很好。我缺少什么才能让它发挥作用?

I'm trying to make the simplest custom shader for Three.js that I can, but I haven't figured out how to make it work. The object the I'm using the shader for doesn't appear at all.

In my page html I have:

<script id="simplefs" type="x-shader/x-fragment">

    void main(void) {
        gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
    }
</script>

<script id="simplevs" type="x-shader/x-vertex">

    void main(void) {
        gl_Position = modelViewMatrix * projectionMatrix * vec4(position, 1.0);
    }
</script>

Then in javascript:

var vertShader = document.getElementById("simplevs").innerHTML;
var fragShader = document.getElementById("simplefs").innerHTML;

var myMaterial = new THREE.ShaderMaterial({
    vertexShader : vertShader,
    fragmentShader: fragShader
});

var baseBevel = new THREE.Mesh(new THREE.CylinderGeometry(BaseRadius - BaseBevel, BaseRadius, BaseBevel, 100, 100, false),
                               myMaterial )
baseBevel.position.x = x;
baseBevel.position.y = y;
baseBevel.position.z = BaseHeight - (BaseBevel / 2.0);
baseBevel.rotation.x = Math.PI / 2.0;

scene.add(baseBevel); 

Where the object should be, there is nothing. It works fine if I replace the material with a MeshLambertMaterial. What am I missing that I need to make it work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾听心声的旋律 2025-01-03 07:31:22

解决方法很简单,顶点着色器中矩阵乘法的顺序需要改为:

gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

Easy solution, the order of the matrix multiplication in the vertex shader needs to be changed to:

gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文