Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- ==============================================================================
- This is an automatically generated GUI class created by the Introjucer!
- Be careful when adding custom code to these files, as only the code within
- the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded
- and re-saved.
- Created with Introjucer version: 3.1.1
- ------------------------------------------------------------------------------
- The Introjucer is part of the JUCE library - "Jules' Utility Class Extensions"
- Copyright 2004-13 by Raw Material Software Ltd.
- ==============================================================================
- */
- //[Headers] You can add your own extra header files here...
- //[/Headers]
- #include "HeadAnimation.h"
- //[MiscUserDefs] You can add your own user definitions and misc code here...
- //[/MiscUserDefs]
- //==============================================================================
- HeadAnimation::HeadAnimation () : doBackgroundDrawing(false),
- scale(0.5f), rotationSpeed(0.0f), rotation(0.0f),
- textureToUse(nullptr), lastTexture(nullptr)
- {
- //[UserPreSize]
- //[/UserPreSize]
- setSize (600, 400);
- //[Constructor] You can add your own custom stuff here..
- const TopLevelWindow* tlw = TopLevelWindow::getTopLevelWindow(0);
- //tlw->setRenderingEngine(0);
- //setOpaque(true);
- //addAndMakeVisible(controlsOverlay = new DemoControlsOverlay(*this));
- openGLContext.setRenderer(this);
- openGLContext.attachTo(*this);
- openGLContext.setContinuousRepainting(true);
- //openGLContext.setRenderer(this);
- textures.add(new BuiltInTexture("Portmeirion", BinaryData::portmeirion_jpg, BinaryData::portmeirion_jpgSize));
- DemoTexture* t = textures[0];
- setTexture(t);
- scale = 1;
- String vertex =
- "attribute vec4 position;\n"
- "attribute vec4 sourceColour;\n"
- "attribute vec2 textureCoordIn;\n"
- "\n"
- "varying vec4 destinationColour;\n"
- "varying vec2 textureCoordOut;\n"
- "\n"
- "void main()\n"
- "{\n"
- " destinationColour = sourceColour;\n"
- " textureCoordOut = textureCoordIn;\n"
- " gl_Position = position;\n"
- "}\n";
- String fragment =
- #if JUCE_OPENGL_ES
- "varying lowp vec4 destinationColour;\n"
- "varying lowp vec2 textureCoordOut;\n"
- #else
- "varying vec4 destinationColour;\n"
- "varying vec2 textureCoordOut;\n"
- #endif
- "\n"
- "uniform sampler2D demoTexture;\n"
- "void main()\n"
- "{\n"
- " gl_FragColor = destinationColour; \n"
- " gl_FragColor = texture2D (demoTexture, textureCoordOut);"
- "}\n";
- //String vertext = "attribute vec4 position;attribute vec4 normal;attribute vec4 sourceColour;attribute vec2 texureCoordIn;uniform mat4 projectionMatrix;uniform mat4 viewMatrix;uniform vec4 lightPosition;varying vec4 destinationColour;varying vec2 textureCoordOut;varying float lightIntensity;void main(){ destinationColour = sourceColour; textureCoordOut = texureCoordIn; vec4 light = viewMatrix * lightPosition; lightIntensity = dot (light, normal); gl_Position = projectionMatrix * viewMatrix * position;}";
- //String fragment = "varying vec4 destinationColour;varying vec2 textureCoordOut;varying float lightIntensity;uniform sampler2D demoTexture;void main(){ float l = max (0.3, lightIntensity * 0.3); vec4 colour = vec4 (l, l, l, 1.0); gl_FragColor = colour * texture2D (demoTexture, textureCoordOut);}";
- setShaderProgram(vertex, fragment);
- doBackgroundDrawing = false;
- //controlsOverlay->initialise();
- //[/Constructor]
- }
- HeadAnimation::~HeadAnimation()
- {
- //[Destructor_pre]. You can add your own custom destruction code here..
- //[/Destructor_pre]
- //[Destructor]. You can add your own custom destruction code here..
- //[/Destructor]
- }
- //==============================================================================
- void HeadAnimation::paint (Graphics& g)
- {
- //[UserPrePaint] Add your own custom painting code here..
- //[/UserPrePaint]
- //g.fillAll (Colour (0xffaaaaaa));
- //[UserPaint] Add your own custom painting code here..
- //[/UserPaint]
- }
- void HeadAnimation::resized()
- {
- //[UserPreResize] Add your own custom resize code here..
- //[/UserPreResize]
- //[UserResized] Add your own custom resize handling here..
- //[/UserResized]
- }
- //[MiscUserCode] You can add your own definitions of your custom methods or any other code here...
- struct DynamicTexture : public DemoTexture
- {
- DynamicTexture() { name = "Dynamically-generated texture"; }
- Image image;
- BouncingNumber x, y;
- bool applyTo(OpenGLTexture& texture) override
- {
- const int size = 128;
- if (!image.isValid())
- image = Image(Image::ARGB, size, size, true);
- {
- Graphics g(image);
- g.fillAll(Colours::lightcyan);
- g.setColour(Colours::darkred);
- g.drawRect(0, 0, size, size, 2);
- g.setColour(Colours::green);
- g.fillEllipse(x.getValue() * size * 0.9f, y.getValue() * size * 0.9f, size * 0.1f, size * 0.1f);
- g.setColour(Colours::black);
- g.setFont(40);
- g.drawFittedText(String(Time::getCurrentTime().getMilliseconds()), image.getBounds(), Justification::centred, 1);
- }
- texture.loadImage(image);
- return true;
- }
- };
- struct TextureFromFile : public DemoTexture
- {
- TextureFromFile(const File& file)
- {
- name = file.getFileName();
- image = resizeImageToPowerOfTwo(ImageFileFormat::loadFrom(file));
- }
- Image image;
- bool applyTo(OpenGLTexture& texture) override
- {
- texture.loadImage(image);
- return false;
- }
- };
- struct Vertex
- {
- float position[3];
- float normal[3];
- float colour[4];
- float texCoord[2];
- };
- struct Attributes
- {
- Attributes(OpenGLContext& openGLContext, OpenGLShaderProgram& shader)
- {
- position = createAttribute(openGLContext, shader, "position");
- normal = createAttribute(openGLContext, shader, "normal");
- sourceColour = createAttribute(openGLContext, shader, "sourceColour");
- texureCoordIn = createAttribute(openGLContext, shader, "texureCoordIn");
- }
- void enable(OpenGLContext& openGLContext)
- {
- if (position != nullptr)
- {
- openGLContext.extensions.glVertexAttribPointer(position->attributeID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
- openGLContext.extensions.glEnableVertexAttribArray(position->attributeID);
- }
- if (normal != nullptr)
- {
- openGLContext.extensions.glVertexAttribPointer(normal->attributeID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)(sizeof(float) * 3));
- openGLContext.extensions.glEnableVertexAttribArray(normal->attributeID);
- }
- if (sourceColour != nullptr)
- {
- openGLContext.extensions.glVertexAttribPointer(sourceColour->attributeID, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)(sizeof(float) * 6));
- openGLContext.extensions.glEnableVertexAttribArray(sourceColour->attributeID);
- }
- if (texureCoordIn != nullptr)
- {
- openGLContext.extensions.glVertexAttribPointer(texureCoordIn->attributeID, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)(sizeof(float) * 10));
- openGLContext.extensions.glEnableVertexAttribArray(texureCoordIn->attributeID);
- }
- }
- void disable(OpenGLContext& openGLContext)
- {
- if (position != nullptr) openGLContext.extensions.glDisableVertexAttribArray(position->attributeID);
- if (normal != nullptr) openGLContext.extensions.glDisableVertexAttribArray(normal->attributeID);
- if (sourceColour != nullptr) openGLContext.extensions.glDisableVertexAttribArray(sourceColour->attributeID);
- if (texureCoordIn != nullptr) openGLContext.extensions.glDisableVertexAttribArray(texureCoordIn->attributeID);
- }
- ScopedPointer<OpenGLShaderProgram::Attribute> position, normal, sourceColour, texureCoordIn;
- private:
- static OpenGLShaderProgram::Attribute* createAttribute(OpenGLContext& openGLContext,
- OpenGLShaderProgram& shader,
- const char* attributeName)
- {
- if (openGLContext.extensions.glGetAttribLocation(shader.getProgramID(), attributeName) < 0)
- return nullptr;
- return new OpenGLShaderProgram::Attribute(shader, attributeName);
- }
- };
- struct Uniforms
- {
- Uniforms(OpenGLContext& openGLContext, OpenGLShaderProgram& shader)
- {
- projectionMatrix = createUniform(openGLContext, shader, "projectionMatrix");
- viewMatrix = createUniform(openGLContext, shader, "viewMatrix");
- texture = createUniform(openGLContext, shader, "demoTexture");
- lightPosition = createUniform(openGLContext, shader, "lightPosition");
- bouncingNumber = createUniform(openGLContext, shader, "bouncingNumber");
- }
- ScopedPointer<OpenGLShaderProgram::Uniform> projectionMatrix, viewMatrix, texture, lightPosition, bouncingNumber;
- private:
- static OpenGLShaderProgram::Uniform* createUniform(OpenGLContext& openGLContext,
- OpenGLShaderProgram& shader,
- const char* uniformName)
- {
- if (openGLContext.extensions.glGetUniformLocation(shader.getProgramID(), uniformName) < 0)
- return nullptr;
- return new OpenGLShaderProgram::Uniform(shader, uniformName);
- }
- };
- struct Shape
- {
- Shape(OpenGLContext& openGLContext)
- {
- if (shapeFile.load(BinaryData::teapot_obj).wasOk())
- for (int i = 0; i < shapeFile.shapes.size(); ++i)
- vertexBuffers.add(new VertexBuffer(openGLContext, *shapeFile.shapes.getUnchecked(i)));
- }
- void draw(OpenGLContext& openGLContext, Attributes& attributes)
- {
- for (int i = 0; i < vertexBuffers.size(); ++i)
- {
- VertexBuffer& vertexBuffer = *vertexBuffers.getUnchecked(i);
- vertexBuffer.bind();
- attributes.enable(openGLContext);
- glDrawElements(GL_TRIANGLES, vertexBuffer.numIndices, GL_UNSIGNED_INT, 0);
- attributes.disable(openGLContext);
- }
- }
- private:
- struct VertexBuffer
- {
- VertexBuffer(OpenGLContext& context, WavefrontObjFile::Shape& shape) : openGLContext(context)
- {
- numIndices = shape.mesh.indices.size();
- openGLContext.extensions.glGenBuffers(1, &vertexBuffer);
- openGLContext.extensions.glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
- Array<Vertex> vertices;
- createVertexListFromMesh(shape.mesh, vertices, Colours::green);
- openGLContext.extensions.glBufferData(GL_ARRAY_BUFFER, vertices.size() * (int) sizeof(Vertex),
- vertices.getRawDataPointer(), GL_STATIC_DRAW);
- openGLContext.extensions.glGenBuffers(1, &indexBuffer);
- openGLContext.extensions.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
- openGLContext.extensions.glBufferData(GL_ELEMENT_ARRAY_BUFFER, numIndices * (int) sizeof(juce::uint32),
- shape.mesh.indices.getRawDataPointer(), GL_STATIC_DRAW);
- }
- ~VertexBuffer()
- {
- openGLContext.extensions.glDeleteBuffers(1, &vertexBuffer);
- openGLContext.extensions.glDeleteBuffers(1, &indexBuffer);
- }
- void bind()
- {
- openGLContext.extensions.glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
- openGLContext.extensions.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
- }
- GLuint vertexBuffer, indexBuffer;
- int numIndices;
- OpenGLContext& openGLContext;
- JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(VertexBuffer)
- };
- WavefrontObjFile shapeFile;
- OwnedArray<VertexBuffer> vertexBuffers;
- static void createVertexListFromMesh(const WavefrontObjFile::Mesh& mesh, Array<Vertex>& list, Colour colour)
- {
- const float scale = 0.2f;
- WavefrontObjFile::TextureCoord defaultTexCoord = { 0.5f, 0.5f };
- WavefrontObjFile::Vertex defaultNormal = { 0.5f, 0.5f, 0.5f };
- for (int i = 0; i < mesh.vertices.size(); ++i)
- {
- const WavefrontObjFile::Vertex& v = mesh.vertices.getReference(i);
- const WavefrontObjFile::Vertex& n
- = i < mesh.normals.size() ? mesh.normals.getReference(i) : defaultNormal;
- const WavefrontObjFile::TextureCoord& tc
- = i < mesh.textureCoords.size() ? mesh.textureCoords.getReference(i) : defaultTexCoord;
- Vertex vert =
- {
- { scale * v.x, scale * v.y, scale * v.z, },
- { scale * n.x, scale * n.y, scale * n.z, },
- { colour.getFloatRed(), colour.getFloatGreen(), colour.getFloatBlue(), colour.getFloatAlpha() },
- { tc.x, tc.y }
- };
- list.add(vert);
- }
- }
- };
- //void HeadAnimation::selectTexture(int itemID)
- //{
- // if (itemID == 1000)
- // {
- // static File lastLocation = File::getSpecialLocation(File::userPicturesDirectory);
- //
- // FileChooser fc("Choose an image to open...", lastLocation, "*.jpg;*.jpeg;*.png;*.gif");
- //
- // if (fc.browseForFileToOpen())
- // {
- // lastLocation = fc.getResult();
- //
- // textures.add(new TextureFromFile(fc.getResult()));
- // updateTexturesList();
- //
- // textureBox.setSelectedId(textures.size());
- // }
- // }
- // else
- // {
- // if (DemoTexture* t = textures[itemID - 1])
- // demo.setTexture(t);
- // }
- //}
- void HeadAnimation::setShaderProgram(const String& vertexShader, const String& fragmentShader)
- {
- newVertexShader = vertexShader;
- newFragmentShader = fragmentShader;
- }
- void HeadAnimation::setTexture(DemoTexture* t)
- {
- lastTexture = textureToUse = t;
- }
- void HeadAnimation::drawBackground2DStuff(float desktopScale)
- {
- // Create an OpenGLGraphicsContext that will draw into this GL window..
- ScopedPointer<LowLevelGraphicsContext> glRenderer(createOpenGLGraphicsContext(openGLContext,
- roundToInt(desktopScale * getWidth()),
- roundToInt(desktopScale * getHeight())));
- if (glRenderer != nullptr)
- {
- Graphics g(*glRenderer);
- g.addTransform(AffineTransform::scale(desktopScale));
- for (int i = 0; i < numElementsInArray(stars); ++i)
- {
- float size = 0.25f;
- // This stuff just creates a spinning star shape and fills it..
- Path p;
- p.addStar(Point<float>(getWidth() * stars[i].x.getValue(),
- getHeight() * stars[i].y.getValue()), 7,
- getHeight() * size * 0.5f,
- getHeight() * size,
- stars[i].angle.getValue());
- float hue = stars[i].hue.getValue();
- g.setGradientFill(ColourGradient(Colours::green.withRotatedHue(hue).withAlpha(0.8f),
- 0, 0,
- Colours::red.withRotatedHue(hue).withAlpha(0.5f),
- 0, (float)getHeight(), false));
- g.fillPath(p);
- }
- }
- }
- void HeadAnimation::updateShader()
- {
- if (newVertexShader.isNotEmpty() || newFragmentShader.isNotEmpty())
- {
- ScopedPointer<OpenGLShaderProgram> newShader(new OpenGLShaderProgram(openGLContext));
- String statusText;
- if (newShader->addVertexShader(OpenGLHelpers::translateVertexShaderToV3(newVertexShader))
- && newShader->addFragmentShader(OpenGLHelpers::translateFragmentShaderToV3(newFragmentShader))
- && newShader->link())
- {
- shape = nullptr;
- attributes = nullptr;
- uniforms = nullptr;
- shader = newShader;
- shader->use();
- shape = new Shape(openGLContext);
- attributes = new Attributes(openGLContext, *shader);
- uniforms = new Uniforms(openGLContext, *shader);
- statusText = "GLSL: v" + String(OpenGLShaderProgram::getLanguageVersion(), 2);
- }
- else
- {
- statusText = newShader->getLastError();
- }
- //controlsOverlay->statusLabel.setText(statusText, dontSendNotification);
- newVertexShader = String::empty;
- newFragmentShader = String::empty;
- }
- }
- void HeadAnimation::renderOpenGL()
- {
- jassert(OpenGLHelpers::isContextActive());
- const float desktopScale = (float)openGLContext.getRenderingScale();
- OpenGLHelpers::clear(Colours::lightblue);
- if (textureToUse != nullptr)
- {
- if (!textureToUse->applyTo(texture))
- {
- textureToUse = nullptr;
- }
- }
- // First draw our background graphics to demonstrate the OpenGLGraphicsContext class
- if (doBackgroundDrawing)
- drawBackground2DStuff(desktopScale);
- updateShader(); // Check whether we need to compile a new shader
- if (shader == nullptr)
- return;
- // Having used the juce 2D renderer, it will have messed-up a whole load of GL state, so
- // we need to initialise some important settings before doing our normal GL 3D drawing..
- glEnable(GL_DEPTH_TEST);
- glDepthFunc(GL_LESS);
- glEnable(GL_BLEND);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- openGLContext.extensions.glActiveTexture(GL_TEXTURE0);
- glEnable(GL_TEXTURE_2D);
- glViewport(0, 0, roundToInt(desktopScale * getWidth()), roundToInt(desktopScale * getHeight()));
- texture.bind();
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
- shader->use();
- if (uniforms->projectionMatrix != nullptr)
- uniforms->projectionMatrix->setMatrix4(getProjectionMatrix().mat, 1, false);
- if (uniforms->viewMatrix != nullptr)
- uniforms->viewMatrix->setMatrix4(getViewMatrix().mat, 1, false);
- if (uniforms->texture != nullptr)
- uniforms->texture->set((GLint)0);
- if (uniforms->lightPosition != nullptr)
- uniforms->lightPosition->set(-15.0f, 10.0f, 15.0f, 0.0f);
- if (uniforms->bouncingNumber != nullptr)
- uniforms->bouncingNumber->set(bouncingNumber.getValue());
- shape->draw(openGLContext, *attributes);
- // Reset the element buffers so child Components draw correctly
- openGLContext.extensions.glBindBuffer(GL_ARRAY_BUFFER, 0);
- openGLContext.extensions.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
- rotation += (float)rotationSpeed;
- }
- void HeadAnimation::newOpenGLContextCreated()
- {
- // nothing to do in this case - we'll initialise our shaders + textures
- // on demand, during the render callback.
- freeAllContextObjects();
- //if (controlsOverlay != nullptr) controlsOverlay->updateShader();
- }
- void HeadAnimation::openGLContextClosing()
- {
- // When the context is about to close, you must use this callback to delete
- // any GPU resources while the context is still current.
- freeAllContextObjects();
- //if (lastTexture != nullptr) setTexture(lastTexture);
- }
- void HeadAnimation::freeAllContextObjects()
- {
- shape = nullptr;
- shader = nullptr;
- attributes = nullptr;
- uniforms = nullptr;
- texture.release();
- }
- Matrix3D<float> HeadAnimation::getProjectionMatrix() const
- {
- float w = 1.0f / (scale + 0.1f);
- float h = w * getLocalBounds().toFloat().getAspectRatio(false);
- return Matrix3D<float>::fromFrustum(-w, w, -h, h, 4.0f, 30.0f);
- }
- Matrix3D<float> HeadAnimation::getViewMatrix() const
- {
- Matrix3D<float> viewMatrix = draggableOrientation.getRotationMatrix()
- * Vector3D<float>(0.0f, 1.0f, -10.0f);
- Matrix3D<float> rotationMatrix = viewMatrix.rotated(Vector3D<float>(rotation, rotation, -0.3f));
- return rotationMatrix * viewMatrix;
- }
- //[/MiscUserCode]
- //==============================================================================
- #if 0
- /* -- Introjucer information section --
- This is where the Introjucer stores the metadata that describe this GUI layout, so
- make changes in here at your peril!
- BEGIN_JUCER_METADATA
- <JUCER_COMPONENT documentType="Component" className="HeadAnimation" componentName=""
- parentClasses="public CPIComponent, private OpenGLRenderer" constructorParams=""
- variableInitialisers="" snapPixels="8" snapActive="1" snapShown="1"
- overlayOpacity="0.330" fixedSize="0" initialWidth="600" initialHeight="400">
- <BACKGROUND backgroundColour="ffaaaaaa"/>
- </JUCER_COMPONENT>
- END_JUCER_METADATA
- */
- #endif
- //[EndFile] You can add extra defines here...
- //[/EndFile]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement