2015-12-27 3 views
10

У меня возникли проблемы с попыткой получить простой квадратик с текстурной картой для запуска на симуляторе iOS. Я прочитал здесь все другие вопросы, которые касаются подобных вещей, и я застрял. Результат выглядит следующим образом:iOS Custom Geometry in SceneKit

enter image description here

текстура этого:

enter image description here

Мой код заключается в следующем:

// v1 +----+ v0 
    // | | 
    // v2 +----+ v3 



    SCNVector3 vertices[] = { SCNVector3Make( 5.0, 5.0, 0.0), 
          SCNVector3Make(-5.0, 5.0, 0.0), 
          SCNVector3Make(-5.0, -5.0, 0.0), 
          SCNVector3Make( 5.0, -5.0, 0.0) 
    }; 

    SCNVector3 normals[] = { SCNVector3Make(0.0f, 0.0f, 1.0), 
          SCNVector3Make(0.0f, 0.0f, 1.0), 
          SCNVector3Make(0.0f, 0.0f, 1.0), 
          SCNVector3Make(0.0f, 0.0f, 1.0) 
    }; 

    CGPoint textureCoordinates[] = { CGPointMake(1.0, 1.0), 
            CGPointMake(0.0, 1.0), 
            CGPointMake(0.0, 0.0), 
            CGPointMake(1.0, 0.0) 
    }; 

    NSUInteger vertexCount = 4; 


    NSMutableData *indicesData = [NSMutableData data]; 
    UInt8 indices[] = { 0, 1, 2, 0, 2, 3}; 
    [indicesData appendBytes:indices length:sizeof(UInt8)*6]; 
    SCNGeometryElement *indicesElement = [SCNGeometryElement geometryElementWithData:indicesData 
                    primitiveType:SCNGeometryPrimitiveTypeTriangles 
                    primitiveCount:2 
                    bytesPerIndex:sizeof(UInt8)]; 

    NSMutableData *vertexData = [NSMutableData dataWithBytes:vertices length:vertexCount * sizeof(SCNVector3)]; 

    SCNGeometrySource *verticesSource = [SCNGeometrySource geometrySourceWithData:vertexData 
                     semantic:SCNGeometrySourceSemanticVertex 
                    vectorCount:vertexCount 
                   floatComponents:YES 
                  componentsPerVector:3 
                   bytesPerComponent:sizeof(float) 
                    dataOffset:0 
                    dataStride:sizeof(SCNVector3)]; 

    NSMutableData *normalData = [NSMutableData dataWithBytes:normals length:vertexCount * sizeof(SCNVector3)]; 

    SCNGeometrySource *normalsSource = [SCNGeometrySource geometrySourceWithData:normalData 
                     semantic:SCNGeometrySourceSemanticNormal 
                    vectorCount:vertexCount 
                   floatComponents:YES 
                  componentsPerVector:3 
                  bytesPerComponent:sizeof(float) 
                    dataOffset:0 
                    dataStride:sizeof(SCNVector3)]; 

    NSMutableData *textureData = [NSMutableData dataWithBytes:textureCoordinates length:vertexCount * sizeof(CGPoint)]; 

    SCNGeometrySource *textureSource = [SCNGeometrySource geometrySourceWithData:textureData 
                     semantic:SCNGeometrySourceSemanticTexcoord 
                    vectorCount:vertexCount 
                   floatComponents:YES 
                  componentsPerVector:2 
                  bytesPerComponent:sizeof(float) 
                    dataOffset:0 
                    dataStride:sizeof(CGPoint)]; 
SCNGeometry *geometry = [SCNGeometry geometryWithSources:@[verticesSource, normalsSource, textureSource] 
                elements:@[indicesElement]]; 


    SCNMaterial *material = [SCNMaterial material]; 
    //material.diffuse.contents = [UIColor redColor]; 
    material.diffuse.contents = [UIImage imageNamed:@"diffuse.jpg"]; 
    material.diffuse.wrapS = SCNWrapModeRepeat; 
    material.diffuse.wrapT = SCNWrapModeRepeat; 
    material.diffuse.contentsTransform = SCNMatrix4MakeScale(1.0f, 1.0f, 1.0f); 
    material.doubleSided = YES; 

    material.normal.wrapS = SCNWrapModeRepeat; 
    material.normal.wrapT = SCNWrapModeRepeat; 
    // material.litPerPixel = YES; 

    geometry.materials = @[material]; 

[Редактировать] Я попробовал много разных вещей с этим кодом и ничего не работает. Мне еще предстоит увидеть рабочий пример в Objective-C, который работает на iOS. Любые изменения в файле material.diffuse.wrapS не влияют.

Я уже делал это в OpenGL без каких-либо проблем, но я смотрел на этот код несколько дней и не вижу своей ошибки. Любая помощь могла бы быть полезна.

+3

Не является CGFloat а * двойной * на 64 бита IOS? Вы указываете * sizeof (float) * для 'byesPerComponent' файла textureSource. –

+0

Никакой разницы, к сожалению, просто попробовал. Спасибо за очень быстрый ответ. – Brett

+0

@ Paul-Jan См. Мой ответ ниже, когда я попробовал ваше предложение, я только изменил его в textureSource, а не в textureData. Посмотрел на это снова и изменился в обоих местах, и это сработало. Если вы хотите написать это как ответ, я соглашусь с этим, иначе я приму свой ответ. – Brett

ответ

11

@ Поль-Ян поставил меня на правильном пути, который приведет меня к этому ответу:

меняет координаты текстуры от CGPoint плавать фиксирует его.

float textureCoordinates[] = { 1.0, 1.0, 
            0.0, 1.0, 
            0.0, 0.0, 
            1.0, 0.0 
    }; 

    NSMutableData *textureData = [NSMutableData dataWithBytes:textureCoordinates length:vertexCount * sizeof(float) * 2]; 

    SCNGeometrySource *textureSource = [SCNGeometrySource geometrySourceWithData:textureData 
                     semantic:SCNGeometrySourceSemanticTexcoord 
                    vectorCount:vertexCount 
                   floatComponents:YES 
                  componentsPerVector:2 
                  bytesPerComponent:sizeof(float) 
                    dataOffset:0 
                    dataStride:sizeof(float) * 2]; 

Результат:

enter image description here

+1

вы можете принять ваш ответ? –

+1

Дает Пол-Ян шанс написать свой комментарий в качестве ответа первым. – Brett

+1

Примите свой ответ, вы сделали всю тяжелую работу, и теперь ваши вопросы и ответы отлично дополняют стопку знаний StackOverflow :) –