Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

как в этом коде применить фрагментный шейдер к точкам: (+ напиши шейдер, который будет…

  1. User

    как в этом коде применить фрагментный шейдер к точкам: (+ напиши шейдер, который будет задавать точкам цвет в зависимости от их положения в пространстве)

    import * as THREE from 'three'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

    const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5;

    const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement);

    const controls = new OrbitControls( camera, renderer.domElement ); controls.enableZoom = false;

    controls.enableDamping = true; controls.dampingFactor = 0.05;

    const loader = new GLTFLoader(); const url = 'GRAF_3_23.glb';

    loader.load(url, function (gltf) { const model = gltf.scene;

    model.traverse((child) => { if (child.isMesh) { const geometry = child.geometry;

      const texture = new THREE.TextureLoader().load('texture3.png');
    
      let startSize = 0.06;
      const sizeVariation = 0.1;
    
      const materialPoint = new THREE.PointsMaterial({
        size: startSize,
        sizeAttenuation: true,
        map: texture,
        alphaTest: 0.01,
        transparent: true,
        color: new THREE.Color(1., 1., 1.),
        opacity: 0.8
      });
    
      const geometryPoint = new THREE.BufferGeometry();
    
      const positions = geometry.getAttribute('position').array;
    
      const randomSize = [];
    
      for (let i = 0; i < positions.length; i += 3) {
        const size = startSize + (Math.random() * sizeVariation);
        randomSize.push(size, size, size);
      }
    
      geometryPoint.setAttribute('size', new THREE.Float32BufferAttribute(randomSize, 1));
    
      const randomPosition = [];
      for (let i = 0; i < positions.length; i += 3) {
        randomPosition.push(10.0*Math.random()-5.0, 10.0*Math.random()-5.0, 10.0*Math.random()-5.0);
      }
      const randomPositionCopy = [...randomPosition];
    
      let increment = 0.002;
    
      geometryPoint.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
    
      const points = new THREE.Points(geometryPoint, materialPoint);
    
    
      geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      function updateArray(increment) {
        for(let j = 0; j < 75; j++) {
          for(let i = 0; i<randomPosition.length; i++) {
            if (randomPosition[i] < positions[i]) {
              randomPosition[i] = randomPosition[i] + increment;
            } else if(randomPosition[i] > positions[i]) {
              randomPosition[i] = randomPosition[i] - increment;
            } else if((randomPosition[i] - positions[i]) < 0.002) {
              randomPosition[i] = positions[i];
            }
          }
        }
        geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      }
      function reverseUpdateArray(increment) {
        for(let j = 0; j < 75; j++) {
          for(let i = 0; i<randomPosition.length; i++) {
            if (randomPosition[i] < randomPositionCopy[i]) {
              randomPosition[i] = randomPosition[i] + increment;
            } else if(randomPosition[i] > randomPositionCopy[i]) {
              randomPosition[i] = randomPosition[i] - increment;
            } else if((randomPosition[i] - randomPositionCopy[i]) < 0.002) {
              randomPosition[i] = randomPositionCopy[i];
            }
          }
        }
        geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      }
    
      let time = 0;
      let sinPosition;
      let sinPosition2;
      let cosPosition;
      let randSignArray = [];
      let sign;
      let ratio = 1.0;
    
      for(let i = 0; i<randomPosition.length; i++) {
        sign = Math.random() < 0.5 ? -1.0 : 1.0;
        randSignArray[i] = sign;
      }
    
      animateVerticles();
      function animateVerticles() {
        requestAnimationFrame(animateVerticles);
        time += 0.1;
        sinPosition = Math.sin(time)*0.1;
        cosPosition = Math.cos(time*0.1)*0.1;
        sinPosition2 = Math.sin(time/Math.PI)*0.1;
        for(let i = 0; i<randomPosition.length; i++) {
          randomPosition[i] += (sinPosition * cosPosition * sinPosition2) * randSignArray[i] * ratio;
        }
        geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      }
    
      window.addEventListener('wheel', function(event) {
        if (event.deltaY > 0) {
          updateArray(increment);
          if(ratio > 0.0) {
            ratio -= 0.01;
          }
        } else {
          reverseUpdateArray(increment);
          ratio += 0.01;
        }
        console.log(ratio);
    
      });
    
      scene.add(points);
      points.rotateX(Math.PI/2.0);
    }
    

    }); camera.position.z = 3;

    function animate() { requestAnimationFrame(animate); controls.update(); renderer.render(scene, camera); } animate(); });

  2. Assistant

    Для применения фрагментного шейдера к точкам необходимо создать новый материал для точек с использованием ShaderMaterial вместо PointsMaterial:

    const materialPoint = new THREE.ShaderMaterial({
      uniforms: {
        depth: { value: 10 },
        color1: { value: new THREE.Color(1.0, 0.0, 0.0) },
        color2: { value: new THREE.Color(0.0, 1.0, 0.0) },
      },
      vertexShader: document.getElementById('vertexShader').textContent,
      fragmentShader: document.getElementById('fragmentShader').textContent,
    });
    

    Здесь мы создаем новый ShaderMaterial, который принимает в качестве параметров uniforms: depth (глубина точки в пространстве), color1 и color2 (цвета для градиента). Кроме того, мы загружаем вершинный и фрагментный шейдеры из элементов с id "vertexShader" и "fragmentShader" соответственно.

    Шейдеры могут выглядеть примерно следующим образом:

    Vertex Shader:

    attribute float size;
    varying vec4 vColor;
    void main() {
      vColor = vec4(mix(color1, color2, position.z / depth), 1.0);
      vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
      gl_PointSize = size * (300.0 / length(mvPosition.xyz));
      gl_Position = projectionMatrix * mvPosition;
    }
    

    Fragment Shader:

    varying vec4 vColor;
    void main() {
      gl_FragColor = vColor;
      if (length(gl_PointCoord - vec2(0.5, 0.5)) > 0.5) {
        discard;
      }
    }
    

    Здесь мы определяем шейдер для точек с использованием атрибута размера и передаем цвет каждой точки в переменную vColor, которую мы передаем во фрагментный шейдер. В фрагментном шейдере мы устанавливаем цвет точки равным vColor, а затем отбрасываем все точки, которые находятся за пределами круга радиусом 0,5 вокруг центра точки.

    Чтобы использовать эти шейдеры, необходимо добавить их на веб-страницу в теги script:

    <script id="vertexShader" type="x-shader/x-vertex">
      // Вставьте код вершинного шейдера здесь
    </script>
    
    <script id="fragmentShader" type="x-shader/x-fragment">
      // Вставьте код фрагментного шейдера здесь
    </script>
    

    После этого мы можем использовать новый материал materialPoint вместо materialPoints в нашем коде, чтобы применить фрагментный шейдер к точкам.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.