/*
HMGLView.m

Author: Makoto Kinoshita

Copyright 2004-2006 The Shiira Project. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions 
  and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of 
  conditions and the following disclaimer in the documentation and/or other materials provided 
  with the distribution.

THIS SOFTWARE IS PROVIDED BY THE SHIIRA PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE SHIIRA PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

#import "HMGLView.h"

#import "HMGLText.h"
#import "HMGLImage.h"

@implementation HMGLView

//--------------------------------------------------------------//
#pragma mark -- Initialize --
//--------------------------------------------------------------//

+ (NSOpenGLPixelFormat*)defaultPixelFormat
{
    static NSOpenGLPixelFormat* pixelFormat = nil;
    if (!pixelFormat) {
        static const NSOpenGLPixelFormatAttribute   attr[] = {
            NSOpenGLPFAWindow,
            
            NSOpenGLPFADoubleBuffer,
            NSOpenGLPFAColorSize, 24,
            NSOpenGLPFAAlphaSize, 8,
            NSOpenGLPFADepthSize, 24,
            
            NSOpenGLPFANoRecovery,
            0
        };
        
        pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:(void*)&attr];
    }
    
    return pixelFormat;
}

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame pixelFormat:[[self class] defaultPixelFormat]];
    if (!self) {
        return nil;
    }
    
    // Initialize instance variables
    _backgroundColor = [[NSColor blackColor] retain];
    
    // Open GL configuration
    GLint   param;
    void*   context;
    context = [[self openGLContext] CGLContextObj];
    
    param = 1;
    CGLSetParameter(context, kCGLCPSwapInterval, &param);
    
    param = 0;
    CGLSetParameter(context, kCGLCPSurfaceOpacity, &param);
    
    return self;
}

- (void)dealloc
{
    [_backgroundColor release];
    
    [super dealloc];
}

//--------------------------------------------------------------//
#pragma mark -- View attributes --
//--------------------------------------------------------------//

- (NSColor*)backgroundColor
{
    return _backgroundColor;
}

- (void)setBackgroundColor:(NSColor*)backgroundColor
{
    _backgroundColor = [backgroundColor retain];
    
    [self setNeedsDisplay:YES];
}

//--------------------------------------------------------------//
#pragma mark -- Drawing --
//--------------------------------------------------------------//

- (void)_updateViewport
{
    // Get bounds
    NSRect  bounds;
    bounds = [self bounds];
    
    // Update viewport
	glViewport(0, 0, bounds.size.width, bounds.size.height);
    
    // Update projection
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
    
    GLdouble    fovy, aspect, near, far;
    fovy = 30.0;
    aspect = bounds.size.width / bounds.size.height;
    near = 1.0;
    far = 1000.0;
    gluPerspective(fovy, aspect, near, far);
    
    // Update model
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

- (void)drawRect:(NSRect)rect
{
    // Update viewport
    [self _updateViewport];
    
    // Clear OpenGL
    if (_backgroundColor) {
        glClearColor([_backgroundColor redComponent], [_backgroundColor greenComponent], 
                [_backgroundColor blueComponent], [_backgroundColor alphaComponent]);
    }
    else {
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    }
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    // Get depth test status
    GLboolean   depthTest;
    depthTest = glIsEnabled(GL_DEPTH_TEST);
    
    // Get width and height
    GLfloat viewport[4], width, height;
    glGetFloatv(GL_VIEWPORT, viewport);
    width = viewport[2];
    height = viewport[3];
    
    // Set up GL
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glEnable(GL_TEXTURE_RECTANGLE_EXT);
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    
    // Set orthographic 1:1 pixel transform in local view coords
    GLint   matrixMode;
    glGetIntegerv(GL_MATRIX_MODE, &matrixMode);
    
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    {
        glLoadIdentity();
        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        {
            glLoadIdentity();
            glScalef(2.0f / width, -2.0f / height, 1.0f);
            glTranslatef(-width / 2.0f, -height / 2.0f, 0.0f);
            
            // Draw image and text
            [self drawTextureInRect:rect];
        }
        
        glPopMatrix();
        glMatrixMode(GL_PROJECTION);
    }
    
    glPopMatrix();
    glMatrixMode(matrixMode);
    
    // Restore GL configuration
    glDisable(GL_TEXTURE_RECTANGLE_EXT);
    glDisable(GL_BLEND);
    if (depthTest) {
        glEnable(GL_DEPTH_TEST);
    }
    
    // Finish OpenGL
	glFinish();
    [[self openGLContext] flushBuffer];
}

- (void)drawTextureInRect:(NSRect)rect
{
    // Do nothing
}

- (BOOL)isOpaque
{
    return NO;
}

@end
