2014-12-02 4 views
0

Я некоторое время использовал BufferGeometry, и я думал, что знаком с ним довольно. Теперь я пытаюсь создать простую квадратную плоскость, и она ничего не делает - никакой видимой плоскости, никаких ошибок и никаких очевидных проблем, насколько я могу судить. Я видел другие сообщения, похожие на них, но ни одно из решений не было успешным.BufferGeometry not visible

Когда я осматриваю сцену, сетка там, у нее есть правильный материал, и ее геометрия, кажется, настроена правильно. Но все, что я получаю, это черный видовой экран. Я должен упустить болезненный, очевидный/простой шаг, но сейчас он уклоняется от меня. Что я делаю не так?

Fiddle + код: http://jsfiddle.net/TheJim01/kafybhge/34/

// BufferGeometry Tester 

var hostDiv, scene, renderer, camera, root, controls, light; 

var WIDTH = 500;//window.innerWidth, 
    HEIGHT = 500;//window.innerHeight, 
    FOV = 35, 
    NEAR = 1, 
    FAR = 1000; 

function createBufferGeometryMesh(){ 
    var geo = new THREE.BufferGeometry(); 

    var vertices = 
     [ 
      -10., 10., 0., // 0 - top left 
      10., 10., 0., // 1 - top right 
      10., -10., 0., // 2 - bottom right 
      -10., -10., 0. // 3 - bottom left 
     ], 
    normals = 
     [ 
      0., 0., 1., 
      0., 0., 1., 
      0., 0., 1., 
      0., 0., 1. 
     ], 
    indices = [ 0, 1, 2, 0, 2, 3 ]; 

    geo.addAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3)); 
    geo.addAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), 3)); 
    geo.addAttribute('index', new THREE.BufferAttribute(new Uint32Array(indices), 1)); 

    var mat = new THREE.MeshPhongMaterial({ 
        color: 0xffffff, 
        ambient: 0xffffff, 
        specular: 0xffffff, 
        shininess: 50, 
        side: THREE.DoubleSide 
       }); 

    var msh = new THREE.Mesh(geo, mat); 

    return msh; 
} 

function init() { 
    hostDiv = document.createElement('div'); 
    document.body.appendChild(hostDiv); 

    renderer = new THREE.WebGLRenderer({ antialias: true }); 
    renderer.setSize(WIDTH, HEIGHT); 
    hostDiv.appendChild(renderer.domElement); 

    camera = new THREE.PerspectiveCamera(FOV, WIDTH/HEIGHT, NEAR, FAR); 
    camera.position.z = 50; 

    controls = new THREE.TrackballControls(camera, renderer.domElement); 

    light = new THREE.PointLight(0xffffff, 1, 1000); 
    light.position.copy(camera.position); 

    scene = new THREE.Scene(); 
    scene.add(camera); 
    scene.add(light); 

    var square = createBufferGeometryMesh(); 
    scene.add(square); 

    animate(); 
} 

function render() { 
    renderer.render(scene, camera); 
} 

function animate() { 
    light.position.copy(camera.position);  

    requestAnimationFrame(animate); 
    render(); 
    controls.update(); 
} 

init(); 

Просто, чтобы показать, что я не новичок в BufferGeometry, вот что-то я делал ранее, который работает, если я подключить его в свой код вместо выше createBufferGeometryMesh() , Я попытался определить буферы, как показано ниже (и даже явно), но ничего не изменил.

function colorCube(scale){ 
    scale = scale || 1; 
    var geo = new THREE.BufferGeometry(); 

    var positions = new Float32Array(72); 
    var normals = new Float32Array(72); 
    var colors = new Float32Array(72); 
    var indices = new Uint16Array(36); 

    var face = 0, idx = 0, vert = 0; 
    var x = 0, r = 0, y = 1, g = 1, z = 2, b = 2; 

    // front face (RED) 
    positions[vert + x] = 0.5; positions[vert + y] = 0.5; positions[vert + z] = 0.5; 
    normals[vert + x] = 0.; normals[vert + y] = 0.; normals[vert + z] = 1.; 
    colors[vert + r] = 1.; colors[vert + g] = 0.; colors[vert + b] = 0.; 
    vert += 3; 

    positions[vert + x] = -0.5; positions[vert + y] = 0.5; positions[vert + z] = 0.5; 
    normals[vert + x] = 0.; normals[vert + y] = 0.; normals[vert + z] = 1.; 
    colors[vert + r] = 1.; colors[vert + g] = 0.; colors[vert + b] = 0.; 
    vert += 3; 

    positions[vert + x] = -0.5; positions[vert + y] = -0.5; positions[vert + z] = 0.5; 
    normals[vert + x] = 0.; normals[vert + y] = 0.; normals[vert + z] = 1.; 
    colors[vert + r] = 1.; colors[vert + g] = 0.; colors[vert + b] = 0.; 
    vert += 3; 

    positions[vert + x] = 0.5; positions[vert + y] = -0.5; positions[vert + z] = 0.5; 
    normals[vert + x] = 0.; normals[vert + y] = 0.; normals[vert + z] = 1.; 
    colors[vert + r] = 1.; colors[vert + g] = 0.; colors[vert + b] = 0.; 
    vert += 3; 

    indices[idx + 0] = (face * 4) + 0; indices[idx + 1] = (face * 4) + 1; indices[idx + 2] = (face * 4) + 2; 
    indices[idx + 3] = (face * 4) + 0; indices[idx + 4] = (face * 4) + 2; indices[idx + 5] = (face * 4) + 3; 
    idx += 6; 
    ++face; 

    // back face (BLUE) 
    positions[vert + x] = -0.5; positions[vert + y] = 0.5; positions[vert + z] = -0.5; 
    normals[vert + x] = 0.; normals[vert + y] = 0.; normals[vert + z] = -1.; 
    colors[vert + r] = 0.; colors[vert + g] = 0.; colors[vert + b] = 1.; 
    vert += 3; 

    positions[vert + x] = 0.5; positions[vert + y] = 0.5; positions[vert + z] = -0.5; 
    normals[vert + x] = 0.; normals[vert + y] = 0.; normals[vert + z] = -1.; 
    colors[vert + r] = 0.; colors[vert + g] = 0.; colors[vert + b] = 1.; 
    vert += 3; 

    positions[vert + x] = 0.5; positions[vert + y] = -0.5; positions[vert + z] = -0.5; 
    normals[vert + x] = 0.; normals[vert + y] = 0.; normals[vert + z] = -1.; 
    colors[vert + r] = 0.; colors[vert + g] = 0.; colors[vert + b] = 1.; 
    vert += 3; 

    positions[vert + x] = -0.5; positions[vert + y] = -0.5; positions[vert + z] = -0.5; 
    normals[vert + x] = 0.; normals[vert + y] = 0.; normals[vert + z] = -1.; 
    colors[vert + r] = 0.; colors[vert + g] = 0.; colors[vert + b] = 1.; 
    vert += 3; 

    indices[idx + 0] = (face * 4) + 0; indices[idx + 1] = (face * 4) + 1; indices[idx + 2] = (face * 4) + 2; 
    indices[idx + 3] = (face * 4) + 0; indices[idx + 4] = (face * 4) + 2; indices[idx + 5] = (face * 4) + 3; 
    idx += 6; 
    ++face; 

    // right face (GREEN) 
    positions[vert + x] = 0.5; positions[vert + y] = 0.5; positions[vert + z] = -0.5; 
    normals[vert + x] = 1.; normals[vert + y] = 0.; normals[vert + z] = 0.; 
    colors[vert + r] = 0.; colors[vert + g] = 1.; colors[vert + b] = 0.; 
    vert += 3; 

    positions[vert + x] = 0.5; positions[vert + y] = 0.5; positions[vert + z] = 0.5; 
    normals[vert + x] = 1.; normals[vert + y] = 0.; normals[vert + z] = 0.; 
    colors[vert + r] = 0.; colors[vert + g] = 1.; colors[vert + b] = 0.; 
    vert += 3; 

    positions[vert + x] = 0.5; positions[vert + y] = -0.5; positions[vert + z] = 0.5; 
    normals[vert + x] = 1.; normals[vert + y] = 0.; normals[vert + z] = 0.; 
    colors[vert + r] = 0.; colors[vert + g] = 1.; colors[vert + b] = 0.; 
    vert += 3; 

    positions[vert + x] = 0.5; positions[vert + y] = -0.5; positions[vert + z] = -0.5; 
    normals[vert + x] = 1.; normals[vert + y] = 0.; normals[vert + z] = 0.; 
    colors[vert + r] = 0.; colors[vert + g] = 1.; colors[vert + b] = 0.; 
    vert += 3; 

    indices[idx + 0] = (face * 4) + 0; indices[idx + 1] = (face * 4) + 1; indices[idx + 2] = (face * 4) + 2; 
    indices[idx + 3] = (face * 4) + 0; indices[idx + 4] = (face * 4) + 2; indices[idx + 5] = (face * 4) + 3; 
    idx += 6; 
    ++face; 

    // left face (MAGENTA) 
    positions[vert + x] = -0.5; positions[vert + y] = 0.5; positions[vert + z] = 0.5; 
    normals[vert + x] = -1.; normals[vert + y] = 0.; normals[vert + z] = 0.; 
    colors[vert + r] = 1.; colors[vert + g] = 0.; colors[vert + b] = 1.; 
    vert += 3; 

    positions[vert + x] = -0.5; positions[vert + y] = 0.5; positions[vert + z] = -0.5; 
    normals[vert + x] = -1.; normals[vert + y] = 0.; normals[vert + z] = 0.; 
    colors[vert + r] = 1.; colors[vert + g] = 0.; colors[vert + b] = 1.; 
    vert += 3; 

    positions[vert + x] = -0.5; positions[vert + y] = -0.5; positions[vert + z] = -0.5; 
    normals[vert + x] = -1.; normals[vert + y] = 0.; normals[vert + z] = 0.; 
    colors[vert + r] = 1.; colors[vert + g] = 0.; colors[vert + b] = 1.; 
    vert += 3; 

    positions[vert + x] = -0.5; positions[vert + y] = -0.5; positions[vert + z] = 0.5; 
    normals[vert + x] = -1.; normals[vert + y] = 0.; normals[vert + z] = 0.; 
    colors[vert + r] = 1.; colors[vert + g] = 0.; colors[vert + b] = 1.; 
    vert += 3; 

    indices[idx + 0] = (face * 4) + 0; indices[idx + 1] = (face * 4) + 1; indices[idx + 2] = (face * 4) + 2; 
    indices[idx + 3] = (face * 4) + 0; indices[idx + 4] = (face * 4) + 2; indices[idx + 5] = (face * 4) + 3; 
    idx += 6; 
    ++face; 

    // top face (CYAN) 
    positions[vert + x] = 0.5; positions[vert + y] = 0.5; positions[vert + z] = -0.5; 
    normals[vert + x] = 0.; normals[vert + y] = 1.; normals[vert + z] = 0.; 
    colors[vert + r] = 0.; colors[vert + g] = 1.; colors[vert + b] = 1.; 
    vert += 3; 

    positions[vert + x] = -0.5; positions[vert + y] = 0.5; positions[vert + z] = -0.5; 
    normals[vert + x] = 0.; normals[vert + y] = 1.; normals[vert + z] = 0.; 
    colors[vert + r] = 0.; colors[vert + g] = 1.; colors[vert + b] = 1.; 
    vert += 3; 

    positions[vert + x] = -0.5; positions[vert + y] = 0.5; positions[vert + z] = 0.5; 
    normals[vert + x] = 0.; normals[vert + y] = 1.; normals[vert + z] = 0.; 
    colors[vert + r] = 0.; colors[vert + g] = 1.; colors[vert + b] = 1.; 
    vert += 3; 

    positions[vert + x] = 0.5; positions[vert + y] = 0.5; positions[vert + z] = 0.5; 
    normals[vert + x] = 0.; normals[vert + y] = 1.; normals[vert + z] = 0.; 
    colors[vert + r] = 0.; colors[vert + g] = 1.; colors[vert + b] = 1.; 
    vert += 3; 

    indices[idx + 0] = (face * 4) + 0; indices[idx + 1] = (face * 4) + 1; indices[idx + 2] = (face * 4) + 2; 
    indices[idx + 3] = (face * 4) + 0; indices[idx + 4] = (face * 4) + 2; indices[idx + 5] = (face * 4) + 3; 
    idx += 6; 
    ++face; 

    // bottom face (YELLOW) 
    positions[vert + x] = 0.5; positions[vert + y] = -0.5; positions[vert + z] = 0.5; 
    normals[vert + x] = 0.; normals[vert + y] = -1.; normals[vert + z] = 0.; 
    colors[vert + r] = 1.; colors[vert + g] = 1.; colors[vert + b] = 0.; 
    vert += 3; 

    positions[vert + x] = -0.5; positions[vert + y] = -0.5; positions[vert + z] = 0.5; 
    normals[vert + x] = 0.; normals[vert + y] = -1.; normals[vert + z] = 0.; 
    colors[vert + r] = 1.; colors[vert + g] = 1.; colors[vert + b] = 0.; 
    vert += 3; 

    positions[vert + x] = -0.5; positions[vert + y] = -0.5; positions[vert + z] = -0.5; 
    normals[vert + x] = 0.; normals[vert + y] = -1.; normals[vert + z] = 0.; 
    colors[vert + r] = 1.; colors[vert + g] = 1.; colors[vert + b] = 0.; 
    vert += 3; 

    positions[vert + x] = 0.5; positions[vert + y] = -0.5; positions[vert + z] = -0.5; 
    normals[vert + x] = 0.; normals[vert + y] = -1.; normals[vert + z] = 0.; 
    colors[vert + r] = 1.; colors[vert + g] = 1.; colors[vert + b] = 0.; 
    vert += 3; 

    indices[idx + 0] = (face * 4) + 0; indices[idx + 1] = (face * 4) + 1; indices[idx + 2] = (face * 4) + 2; 
    indices[idx + 3] = (face * 4) + 0; indices[idx + 4] = (face * 4) + 2; indices[idx + 5] = (face * 4) + 3; 
    idx += 6; 
    ++face; 

    geo.addAttribute('index', new THREE.BufferAttribute(indices, 1)); 
    geo.addAttribute('position', new THREE.BufferAttribute(positions, 3)); 
    geo.addAttribute('normal', new THREE.BufferAttribute(normals, 3)); 
    geo.addAttribute('color', new THREE.BufferAttribute(colors, 3)); 

    var mat = new THREE.MeshPhongMaterial({ 
        color: 0xffffff, 
        ambient: 0xffffff, 
        specular: 0xffffff, 
        shininess: 50, 
        side: THREE.DoubleSide, 
        vertexColors: THREE.VertexColors 
       });  

    var msh = new THREE.Mesh(geo, mat); 
    msh.scale.multiplyScalar(scale); 

    return msh; 
} 
+1

Вы сделали больше, чем вы переделали :) Попробуйте 'renderer.setClearColor (0x888888, 1);' – WestLangley

+0

Ничего себе, это похоже на то, что я не знаю своей левой руки из правой руки (системы)! Если вы хотите опубликовать ответ, я соглашусь с ним, иначе просто напишите еще один комментарий, и я напишу, как я сработал. – TheJim01

+0

На самом деле, я все еще немного смущен. Я понимаю, что использовал LHS, когда должен был использовать RHS. Но почему нормали игнорировались? Не должно ли явное определение переопределять неявное?Есть много причин, по которым мне нужно, чтобы нормали указывали в разных направлениях, поэтому, если у меня есть гибкость, мои ожидания немного расстраивают. – TheJim01

ответ

0

Поскольку WestLangley является скромным, вот что случилось в моем коде выше.

Мой главный ментальный блокпост состоял в том, что у меня было неправильное представление о функции нормалей относительно чертежных граней. Я пришел к мысли, что нормали вершин могут определять направление лица, но это просто неверно. Вертикальные нормали используются для расчета освещения на поверхности и не имеют никакого отношения к определению направления лица. Это порядок вершин, определяющий направление лица (лицо нормальное). Чтобы добавить к нему, я использовал левую систему, когда three.js использует правую систему.

В моем исходном коде, у меня был:

indices = [ 0, 1, 2, 0, 2, 3 ]; 

Чтобы нарисовать лицо в правильном направлении, это должно было быть:

indices = [ 0, 2, 1, 0, 3, 2 ]; 

различие является тонким, но в моем примере они означают разницу между нормальным лицом, направленным в направлениях -Z vs. + Z, соответственно. Лица столкнулись с неправильным способом получения света. Явные нормали даже не вступили в игру, потому что поверхность все равно не отражала света. Индексирование с использованием правой системы фиксировало направления лица.

С проблемой лица позади меня, я сделал упражнение, чтобы укрепить мое понимание, где я перевернул свои вершинные нормали (еще раз) в противоположном направлении от нормалей лица. Как и ожидалось (на этот раз), квадрат стал черным. Несмотря на то, что лица указывали в правильном направлении, нормали, по сути, сказали GL, чтобы отразить освещение в направлении объекта, превратив его в черную дыру.

Мой отборный орех от этого: направление лица (лицо нормальное) рассчитывается по порядку вершин, составляющих лицо, и использует RHS. Нормали вершин влияют на освещение на лицевой поверхности и не имеют никакого отношения к определению направления лица.