public void setImage() { try { File file = new File("C:\\temp\\java\\OpenGLTest\\resources\\GardenBackExplore.png"); texture = TextureIO.newTexture(file, true); } catch (IOException e) { } }
static { try { shellTop = TextureIO.newTexture(new File(TEXTURE_DIRECTORY + "blueShellTop.jpg"), true); textures = new Texture[] {shellTop}; } catch (Exception e) { e.printStackTrace(); } }
/** * Called back immediately after the OpenGL context is initialized. Can be used to perform * one-time initialization. Run only once. */ @Override public void init(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); // get the OpenGL graphics context glu = new GLU(); // get GL Utilities gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // set background (clear) color gl.glClearDepth(1.0f); // set clear depth value to farthest gl.glEnable(GL_DEPTH_TEST); // enables depth testing gl.glDepthFunc(GL_LEQUAL); // the type of depth test to do gl.glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // best perspective correction gl.glShadeModel(GL_SMOOTH); // blends colors nicely, and smoothes out lighting // Load the texture image try { // Create a OpenGL Texture object from (URL, mipmap, file suffix) // Use URL so that can read from JAR and disk file. texture = TextureIO.newTexture( this.getClass().getResource(textureFileName), false, textureFileType); } catch (GLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Use linear filter for texture if image is larger than the original texture gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Use linear filter for texture if image is smaller than the original texture gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Texture image flips vertically. Shall use TextureCoords class to retrieve // the top, bottom, left and right coordinates, instead of using 0.0f and 1.0f. TextureCoords textureCoords = texture.getImageTexCoords(); textureTop = textureCoords.top(); textureBottom = textureCoords.bottom(); // textureLeft = textureCoords.left(); // textureRight = textureCoords.right(); // Enable the texture texture.enable(gl); // gl.glEnable(GL_TEXTURE_2D); // we want back facing polygons to be filled completely and that we want front // facing polygons to be outlined only. gl.glPolygonMode(GL_BACK, GL_FILL); // Back Face Is Filled In gl.glPolygonMode(GL_FRONT, GL_LINE); // Front Face Is Drawn With Lines for (int x = 0; x < numPoints; x++) { // Loop Through The Y Plane for (int y = 0; y < numPoints; y++) { // Apply The Wave To Our Mesh // xmax is 45. Get 9 after dividing by 5. Subtract 4.5 to centralize. points[x][y][0] = (float) x / 5.0f - 4.5f; points[x][y][1] = (float) y / 5.0f - 4.5f; // Sine wave pattern points[x][y][2] = (float) (Math.sin(Math.toRadians(x / 5.0f * 40.0f))); } } }
private static Texture loadTexture(String str) { Texture temp = null; try { temp = TextureIO.newTexture(new File("res/tex/" + str), true); } catch (IOException e) { e.printStackTrace(); System.out.println("Failed loading: " + str); } return temp; }
/** * Load a texture (must be png) * * @param file path to file */ public void loadTexture(GL2 gl, String file) { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(ImageIO.read(new File(file)), "png", os); InputStream fis = new ByteArrayInputStream(os.toByteArray()); textures.put(file, TextureIO.newTexture(fis, true, TextureIO.PNG)); textures.get(file).enable(gl); } catch (IOException ex) { ex.printStackTrace(); } }
public void surface2File(String basename) throws IOException { if (!readBufferUtil.isValid()) { return; } File file = File.createTempFile(basename + shotNum + "-", ".ppm"); TextureIO.write(readBufferUtil.getTextureData(), file); System.out.println("Wrote: " + file.getAbsolutePath() + ", ..."); shotNum++; readBufferUtil.rewindPixelBuffer(); }
private Texture loadTexture(GL3 gl, String file) throws GLException, IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(ImageIO.read(new File(file)), "png", os); InputStream fis = new ByteArrayInputStream(os.toByteArray()); Texture newTexture = TextureIO.newTexture(fis, true, TextureIO.PNG); newTexture.setTexParameteri(gl, GL3.GL_TEXTURE_WRAP_S, GL3.GL_REPEAT); newTexture.setTexParameteri(gl, GL3.GL_TEXTURE_WRAP_T, GL3.GL_REPEAT); newTexture.setTexParameteri(gl, GL3.GL_TEXTURE_MAG_FILTER, GL3.GL_LINEAR); newTexture.setTexParameteri(gl, GL3.GL_TEXTURE_MIN_FILTER, GL3.GL_LINEAR_MIPMAP_LINEAR); System.out.println("Must flip: " + newTexture.getMustFlipVertically()); return newTexture; }
void copyTextureData2File() { if (!readBufferUtil.isValid()) return; try { File file = File.createTempFile("shot" + shotNum + "-", ".ppm"); TextureIO.write(readBufferUtil.getTextureData(), file); System.out.println("Wrote: " + file.getAbsolutePath() + ", ..."); shotNum++; } catch (IOException ioe) { ioe.printStackTrace(); } readBufferUtil.rewindPixelBuffer(); }
@Override public void init(final GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); glut = new GLUT(); gl.glClearColor(0.5f, 0.5f, 0.5f, 0.0f); try { final URLConnection urlConn = IOUtil.getResource(PNGTstFiles.class, "test-ntscP_3-01-160x90.png"); tex = TextureIO.newTexture( gl, TextureIO.newTextureData( gl.getGLProfile(), urlConn.getInputStream(), false, TextureIO.PNG)); } catch (final Exception e) { e.printStackTrace(); } // tex.bind(gl); // uncomment this and comment the above to see a working texture // makeStripeImage(); // gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1); // gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, // GL2.GL_MODULATE); // gl.glTexParameterf(GL2.GL_TEXTURE_1D, GL.GL_TEXTURE_WRAP_S, // GL.GL_REPEAT); // gl.glTexParameterf(GL2.GL_TEXTURE_1D, GL.GL_TEXTURE_MAG_FILTER, // GL.GL_LINEAR); // gl.glTexParameterf(GL2.GL_TEXTURE_1D, GL.GL_TEXTURE_MIN_FILTER, // GL.GL_LINEAR); // gl.glTexImage1D(GL2.GL_TEXTURE_1D, 0, 3, stripeImageWidth, 0, // GL.GL_RGB, GL.GL_UNSIGNED_BYTE, stripeImageBuf); // gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT); // gl.glTexGeni(GL2.GL_S, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_OBJECT_LINEAR); // gl.glTexGenfv(GL2.GL_S, GL2.GL_OBJECT_PLANE, sgenparams, 0); }
private void loadTextureDataFromResource(String textureResource, boolean generateMipmap) { InputStream is = Texture.class.getResourceAsStream(textureResource); String fileSuffix = null; int idxOfDot = textureResource.lastIndexOf('.'); if (idxOfDot > 0) fileSuffix = textureResource.substring(idxOfDot + 1); try { texture = TextureIO.newTexture(is, generateMipmap, fileSuffix); } catch (IOException ex) { logger.error("Failed to load texture from resource", ex); } catch (GLException ex) { logger.error("Failed to load texture from resource", ex); } }
@Override public void init(GLAutoDrawable dr) { GL2 gl = dr.getGL().getGL2(); // Задает цвет фона gl.glClearColor(0f, 0f, 0f, 0f); gl.glClearDepth(1.0f); // Интерполирует цвет, если вершины заданы различным цветом gl.glShadeModel(GL2.GL_SMOOTH); // Удаления невидимых линий и поверхностей gl.glEnable(GL.GL_DEPTH_TEST); gl.glDepthFunc(GL.GL_LEQUAL); // Сглаживание gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST); // Включение отображения текстур gl.glEnable(GL.GL_TEXTURE_2D); try { this.texture = TextureIO.newTexture(new File("img/earth.jpg"), false); } catch (IOException exception) { exception.printStackTrace(); } }
/** * @param buffer * @param tile * @param pool * @return */ private Tile createTile( FloatBuffer buffer, Rectangle tile, GL gl, Deque<Texture> pool, TablePerspective tablePerspective) { final VirtualArray recordVA = tablePerspective.getRecordPerspective().getVirtualArray(); final VirtualArray dimVA = tablePerspective.getDimensionPerspective().getVirtualArray(); final ATableBasedDataDomain dataDomain = tablePerspective.getDataDomain(); final int ilast = tile.y + tile.height; final int jlast = tile.x + tile.width; // fill buffer buffer.rewind(); for (int i = tile.y; i < ilast; ++i) { int recordID = recordVA.get(i); for (int j = tile.x; j < jlast; ++j) { int dimensionID = dimVA.get(j); Color color = blockColorer.apply(recordID, dimensionID, dataDomain, false); buffer.put(color.getRGBA()); } } // load to texture buffer.rewind(); Texture texture; if (!pool.isEmpty()) texture = pool.poll(); else texture = TextureIO.newTexture(GL.GL_TEXTURE_2D); TextureData texData = asTextureData(buffer, tile.width, tile.height); texture.updateImage(gl, texData); gl.glFlush(); texData.destroy(); return new Tile(tile, texture); }
public void testImpl(boolean useFFP, final InputStream istream) throws InterruptedException, IOException { final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false); GLProfile glp; if (useFFP && GLProfile.isAvailable(GLProfile.GL2)) { glp = GLProfile.getMaxFixedFunc(true); } else if (!useFFP && GLProfile.isAvailable(GLProfile.GL2ES2)) { glp = GLProfile.getGL2ES2(); } else { System.err.println(getSimpleTestName(".") + ": GLProfile n/a, useFFP: " + useFFP); return; } final GLCapabilities caps = new GLCapabilities(glp); caps.setAlphaBits(1); final TextureData texData = TextureIO.newTextureData(glp, istream, false /* mipmap */, TextureIO.TGA); System.err.println("TextureData: " + texData); final GLWindow glad = GLWindow.create(caps); glad.setTitle("TestTGATextureGL2FromFileNEWT"); // Size OpenGL to Video Surface glad.setSize(texData.getWidth(), texData.getHeight()); // load texture from file inside current GL context to match the way // the bug submitter was doing it final GLEventListener gle = useFFP ? new TextureDraw01GL2Listener(texData) : new TextureDraw01ES2Listener(texData, 0); glad.addGLEventListener(gle); glad.addGLEventListener( new GLEventListener() { boolean shot = false; @Override public void init(GLAutoDrawable drawable) {} public void display(GLAutoDrawable drawable) { // 1 snapshot if (null != ((TextureDraw01Accessor) gle).getTexture() && !shot) { shot = true; snapshot(0, null, drawable.getGL(), screenshot, TextureIO.PNG, null); } } @Override public void dispose(GLAutoDrawable drawable) {} @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {} }); Animator animator = new Animator(glad); animator.setUpdateFPSFrames(60, showFPS ? System.err : null); QuitAdapter quitAdapter = new QuitAdapter(); glad.addKeyListener(quitAdapter); glad.addWindowListener(quitAdapter); glad.setVisible(true); animator.start(); while (!quitAdapter.shouldQuit() && animator.isAnimating() && animator.getTotalFPSDuration() < duration) { Thread.sleep(100); } animator.stop(); glad.destroy(); }
protected void runOneSet( GLAutoDrawable drawable, String textBaseName, int numObjs, int numTextures, int loops) { GL2ES2 gl = drawable.getGL().getGL2ES2(); if (numTextures > MAX_TEXTURE_ENGINES) { throw new GLException("numTextures must be within 1.." + MAX_TEXTURE_ENGINES); } String textName = null; textDatas = new TextureData[numObjs]; textures = new Texture[numTextures]; try { for (int i = 0; i < numObjs; i++) { textName = "data/" + textBaseName + "." + (i + 1) + ".tga"; URL urlText = IOUtil.getResource(Perftst.class, textName); if (urlText == null) { throw new RuntimeException("couldn't fetch " + textName); } textDatas[i] = TextureIO.newTextureData(gl.getGLProfile(), urlText.openStream(), false, TextureIO.TGA); System.out.println(textBaseName + ": " + textDatas[i]); } for (int i = 0; i < numTextures; i++) { gl.glActiveTexture(i); textures[i] = new Texture(GL.GL_TEXTURE_2D); } } catch (IOException ioe) { System.err.println("couldn't fetch " + textName); throw new RuntimeException(ioe); } // // Vertices Data setup // st.useProgram(gl, true); GLArrayDataServer vertices = GLArrayDataServer.createGLSL("mgl_Vertex", 2, GL.GL_FLOAT, true, 4, GL.GL_STATIC_DRAW); { FloatBuffer vb = (FloatBuffer) vertices.getBuffer(); vb.put(0f); vb.put(0f); vb.put(1f); vb.put(0f); vb.put(0f); vb.put(1f); vb.put(1f); vb.put(1f); } vertices.seal(gl, true); GLArrayDataServer texCoords = GLArrayDataServer.createGLSL( "mgl_MultiTexCoord0", 2, GL.GL_FLOAT, true, 4, GL.GL_STATIC_DRAW); { FloatBuffer cb = (FloatBuffer) texCoords.getBuffer(); cb.put(0f); cb.put(0f); cb.put(1f); cb.put(0f); cb.put(0f); cb.put(1f); cb.put(1f); cb.put(1f); } texCoords.seal(gl, true); // // texture setup // long[] tU = new long[numObjs + 1]; tU[0] = System.currentTimeMillis(); for (int j = 0; j < numTextures; j++) { gl.glActiveTexture(j); textures[j].updateImage(gl, textDatas[0]); tU[j + 1] = System.currentTimeMillis(); } GLUniformData activeTexture = new GLUniformData("mgl_ActiveTexture", 0); st.uniform(gl, activeTexture); // // run loops // long dtC, dt, dt2, dt3, dtF, dtS, dtT; long[][] tC = new long[loops][numObjs]; long[][] t0 = new long[loops][numObjs]; long[][][] t1 = new long[loops][numObjs][numTextures]; long[][][] t2 = new long[loops][numObjs][numTextures]; long[][][] t3 = new long[loops][numObjs][numTextures]; long[][] tF = new long[loops][numObjs]; long[][] tS = new long[loops][numObjs]; for (int i = 0; i < loops; i++) { for (int j = 0; j < numObjs; j++) { tC[i][j] = System.currentTimeMillis(); gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT); t0[i][j] = System.currentTimeMillis(); for (int k = 0; k < numTextures; k++) { gl.glActiveTexture(GL.GL_TEXTURE0 + k); textures[k].enable(gl); textures[k].bind(gl); activeTexture.setData(k); st.uniform(gl, activeTexture); t1[i][j][k] = System.currentTimeMillis(); textures[k].updateSubImage(gl, textDatas[j], 0, 0, 0); t2[i][j][k] = System.currentTimeMillis(); gl.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, vertices.getElementCount()); t3[i][j][k] = System.currentTimeMillis(); } gl.glFinish(); tF[i][j] = System.currentTimeMillis(); drawable.swapBuffers(); tS[i][j] = System.currentTimeMillis(); /*try { Thread.sleep(100); } catch (Exception e) {} */ } } int textBytes = 0; for (int j = 0; j < numObjs; j++) { textBytes += textDatas[j].getEstimatedMemorySize(); } textBytes *= numTextures; dt = 0; for (int i = 1; i < loops; i++) { for (int j = 0; j < numObjs; j++) { dt += tS[i][j] - tC[i][j]; } } System.out.println(""); System.out.println( "Texture " + textBaseName + ", loops " + loops + ", textures " + numTextures + ", objects " + numObjs + ", total bytes " + textBytes + ", total time: " + dt + "ms, fps(-1): " + (((loops - 1) * numObjs * 1000) / dt) + ",\n text kB/s: " + (((double) (loops * textBytes) / 1024.0) / ((double) dt / 1000.0))); for (int i = 0; i < loops; i++) { dtC = 0; dtF = 0; dtS = 0; dtT = 0; for (int j = 0; j < numObjs; j++) { dtC += t0[i][j] - tC[i][j]; dtF += tF[i][j] - t3[i][j][numTextures - 1]; dtS += tS[i][j] - tF[i][j]; dtT += tS[i][j] - tC[i][j]; } if (dtT <= 0) dtT = 1; System.out.println( "\tloop " + i + ": clear " + dtC + "ms, finish " + dtF + ", swap " + dtS + "ms, total: " + dtT + "ms, fps " + (numObjs * 1000) / dtT); /* for(int j=0; j<dummyUni.length; j++) { dt = t1[i][j] - t0[i]; dt2= t2[i][j] - t1[i][j]; dt3= t3[i][j] - t2[i][j]; dtT= dt+dt2+dt3; System.out.println("\t\tobj "+j+": setup "+dt +"ms, update "+dt2 +"ms, draw "+dt3+"ms, total: "+ dtT); } */ } System.out.println("*****************************************************************"); st.useProgram(gl, false); for (int i = 0; i < numTextures; i++) { textures[i].disable(gl); textures[i].destroy(gl); textures[i] = null; } for (int i = 0; i < numObjs; i++) { textDatas[i] = null; } textures = null; textDatas = null; System.gc(); try { Thread.sleep(100); } catch (Exception e) { } System.gc(); }
public void init(GLAutoDrawable drawable) { if (null != textureData) { this.texture = TextureIO.newTexture(textureData); } }
void doTest( final boolean onscreen, final GLEventListener demo, final GLProfile glp, final int msaaCount) throws IOException { final GLCapabilities caps = new GLCapabilities(glp); caps.setDoubleBuffered(onscreen); if (msaaCount > 0) { caps.setSampleBuffers(true); caps.setNumSamples(msaaCount); } final int maxTileSize = 256; final GLAutoDrawable glad; if (onscreen) { final GLWindow glWin = GLWindow.create(caps); glWin.setSize(maxTileSize, maxTileSize); glWin.setVisible(true); glad = glWin; } else { final GLDrawableFactory factory = GLDrawableFactory.getFactory(glp); glad = factory.createOffscreenAutoDrawable(null, caps, null, maxTileSize, maxTileSize); } glad.addGLEventListener(demo); // Fix the image size for now final int imageWidth = glad.getSurfaceWidth() * 6; final int imageHeight = glad.getSurfaceHeight() * 4; final String filename = this.getSnapshotFilename( 0, "-tile", glad.getChosenGLCapabilities(), imageWidth, imageHeight, false, TextureIO.PNG, null); final File file = new File(filename); // Initialize the tile rendering library final TileRenderer renderer = new TileRenderer(); renderer.setImageSize(imageWidth, imageHeight); renderer.setTileSize(glad.getSurfaceWidth(), glad.getSurfaceHeight(), 0); renderer.attachAutoDrawable(glad); final GLPixelBuffer.GLPixelBufferProvider pixelBufferProvider = GLPixelBuffer.defaultProviderWithRowStride; final boolean[] flipVertically = {false}; final GLEventListener preTileGLEL = new GLEventListener() { @Override public void init(final GLAutoDrawable drawable) { final GL gl = drawable.getGL(); final GLPixelAttributes pixelAttribs = pixelBufferProvider.getAttributes(gl, 3); final GLPixelBuffer pixelBuffer = pixelBufferProvider.allocate(gl, pixelAttribs, imageWidth, imageHeight, 1, true, 0); renderer.setImageBuffer(pixelBuffer); if (drawable.isGLOriented()) { flipVertically[0] = false; } else { flipVertically[0] = true; } } @Override public void dispose(final GLAutoDrawable drawable) {} @Override public void display(final GLAutoDrawable drawable) {} @Override public void reshape( final GLAutoDrawable drawable, final int x, final int y, final int width, final int height) {} }; renderer.setGLEventListener(preTileGLEL, null); while (!renderer.eot()) { renderer.display(); } renderer.detachAutoDrawable(); // Restore viewport and Gear's PMV matrix // .. even though we close the demo, this is for documentation! glad.invoke( true, new GLRunnable() { @Override public boolean run(final GLAutoDrawable drawable) { drawable .getGL() .glViewport(0, 0, drawable.getSurfaceWidth(), drawable.getSurfaceHeight()); demo.reshape(drawable, 0, 0, drawable.getSurfaceWidth(), drawable.getSurfaceHeight()); return false; } }); final GLPixelBuffer imageBuffer = renderer.getImageBuffer(); final TextureData textureData = new TextureData( caps.getGLProfile(), 0 /* internalFormat */, imageWidth, imageHeight, 0, imageBuffer.pixelAttributes, false, false, flipVertically[0], imageBuffer.buffer, null /* Flusher */); TextureIO.write(textureData, file); glad.destroy(); }
@Override public void init(final GLAutoDrawable glad) { if (null != textureData) { texture = TextureIO.newTexture(glad.getGL(), textureData); } final GL2ES2 gl = glad.getGL().getGL2ES2(); initShader(gl, true); // setup mgl_PMVMatrix pmvMatrix = new PMVMatrix(); pmvMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION); pmvMatrix.glLoadIdentity(); pmvMatrix.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); pmvMatrix.glLoadIdentity(); pmvMatrixUniform = new GLUniformData("mgl_PMVMatrix", 4, 4, pmvMatrix.glGetPMvMatrixf()); // P, Mv st.ownUniform(pmvMatrixUniform); if (!st.uniform(gl, pmvMatrixUniform)) { throw new GLException("Error setting PMVMatrix in shader: " + st); } if (!st.uniform(gl, new GLUniformData("mgl_ActiveTexture", textureUnit))) { throw new GLException("Error setting mgl_ActiveTexture in shader: " + st); } if (null != texture) { // fetch the flipped texture coordinates texture.getImageTexCoords().getST_LB_RB_LT_RT(s_quadTexCoords, 0, 1f, 1f); } interleavedVBO = GLArrayDataServer.createGLSLInterleaved( 3 + 4 + 2, GL.GL_FLOAT, false, 3 * 4, GL.GL_STATIC_DRAW); { interleavedVBO.addGLSLSubArray("mgl_Vertex", 3, GL.GL_ARRAY_BUFFER); interleavedVBO.addGLSLSubArray("mgl_Color", 4, GL.GL_ARRAY_BUFFER); // interleavedVBO.addGLSLSubArray("mgl_Normal", 3, GL.GL_ARRAY_BUFFER); interleavedVBO.addGLSLSubArray("mgl_MultiTexCoord", 2, GL.GL_ARRAY_BUFFER); final FloatBuffer ib = (FloatBuffer) interleavedVBO.getBuffer(); for (int i = 0; i < 4; i++) { ib.put(s_quadVertices, i * 3, 3); ib.put(s_quadColors, i * 4, 4); // ib.put(s_cubeNormals, i*3, 3); ib.put(s_quadTexCoords, i * 2, 2); } } interleavedVBO.seal(gl, true); interleavedVBO.enableBuffer(gl, false); st.ownAttribute(interleavedVBO, true); // OpenGL Render Settings gl.glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); gl.glEnable(GL.GL_DEPTH_TEST); if (keepTextureBound && null != texture) { gl.glActiveTexture(GL.GL_TEXTURE0 + textureUnit); texture.enable(gl); texture.bind(gl); } st.useProgram(gl, false); }