Skip to content

Instantly share code, notes, and snippets.

@wchristian
Last active December 29, 2015 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wchristian/d6c28393f31ea2b9a163 to your computer and use it in GitHub Desktop.
Save wchristian/d6c28393f31ea2b9a163 to your computer and use it in GitHub Desktop.
my $Indices = pdl( #
0, 3, 1,
1, 3, 2,
2, 3, 0,
1, 2, 0,
)->long;
CreateVertexBuffer($Indices);
sub CalcNormals {
my ( $pIndices, $IndexCount, $pVertices, $VertexCount ) = @_;
# Accumulate each triangle normal into each of the triangle vertices
for ( my $i = 0 ; $i < $IndexCount ; $i += 3 ) {
my $Index0 = $pIndices->at( $i );
my $Index1 = $pIndices->at( $i + 1 );
my $Index2 = $pIndices->at( $i + 2 );
my $v1 = $pVertices->slice( "($Index1),0:2" ) - $pVertices->slice( "($Index0),0:2" );
my $v2 = $pVertices->slice( "($Index2),0:2" ) - $pVertices->slice( "($Index0),0:2" );
my $Normal = $v1->crossp( $v2 );
$Normal = $Normal->norm;
$pVertices->slice( "5:7,($Index0)" ) += $Normal;
$pVertices->slice( "5:7,($Index1)" ) += $Normal;
$pVertices->slice( "5:7,($Index2)" ) += $Normal;
}
# Normalize all the vertex normals
for my $i ( 0 .. $VertexCount - 1 ) {
$pVertices->slice( "5:7,($i)" ) .= $pVertices->slice( "5:7,($i)" )->norm;
}
}
sub CreateVertexBuffer {
my ( $pIndices ) = @_;
my $v = pdl( #
[ -1, -1, 0.5773, 0, 0, 0, 0, 0 ],
[ 0, -1, -1.15475, 0.5, 0, 0, 0, 0 ],
[ 1, -1, 0.5773, 1, 0, 0, 0, 0 ],
[ 0, 1, 0, 0.5, 1, 0, 0, 0 ],
)->float;
my $type_size = howbig( $v->get_datatype );
$self->VBO_vertex_size( $v->dim( 0 ) * $type_size );
$self->VBO_tex_offset( 3 * $type_size );
$self->VBO_normal_offset( 5 * $type_size );
CalcNormals( $pIndices, $pIndices->nelem, $v, $v->dim( 1 ) );
$self->VBO( glGenBuffersARB_p( 1 ) );
glBindBufferARB( GL_ARRAY_BUFFER, $self->VBO );
glBufferDataARB_s(
GL_ARRAY_BUFFER, #
$v->nelem * $type_size,
$v->get_dataref,
GL_STATIC_DRAW,
);
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment