Best JavaScript code snippet using wpt
get_gen.py
Source:get_gen.py
1#!/usr/bin/env python2# Mesa 3-D graphics library3#4# Copyright (C) 1999-2006 Brian Paul All Rights Reserved.5#6# Permission is hereby granted, free of charge, to any person obtaining a7# copy of this software and associated documentation files (the "Software"),8# to deal in the Software without restriction, including without limitation9# the rights to use, copy, modify, merge, publish, distribute, sublicense,10# and/or sell copies of the Software, and to permit persons to whom the11# Software is furnished to do so, subject to the following conditions:12#13# The above copyright notice and this permission notice shall be included14# in all copies or substantial portions of the Software.15#16# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS17# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,18# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL19# BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN20# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN21# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.22# This script is used to generate the get.c file:23# python get_gen.py > get.c24import string25GLint = 126GLenum = 227GLfloat = 328GLdouble = 429GLboolean = 530GLfloatN = 6 # A normalized value, such as a color or depth range31TypeStrings = {32 GLint : "GLint",33 GLenum : "GLenum",34 GLfloat : "GLfloat",35 GLdouble : "GLdouble",36 GLboolean : "GLboolean"37}38# Each entry is a tuple of:39# - the GL state name, such as GL_CURRENT_COLOR40# - the state datatype, one of GLint, GLfloat, GLboolean or GLenum41# - list of code fragments to get the state, such as ["ctx->Foo.Bar"]42# - optional extra code or empty string43# - optional extensions to check, or None44#45StateVars = [46 ( "GL_ACCUM_RED_BITS", GLint, ["ctx->DrawBuffer->Visual.accumRedBits"],47 "", None ),48 ( "GL_ACCUM_GREEN_BITS", GLint, ["ctx->DrawBuffer->Visual.accumGreenBits"],49 "", None ),50 ( "GL_ACCUM_BLUE_BITS", GLint, ["ctx->DrawBuffer->Visual.accumBlueBits"],51 "", None ),52 ( "GL_ACCUM_ALPHA_BITS", GLint, ["ctx->DrawBuffer->Visual.accumAlphaBits"],53 "", None ),54 ( "GL_ACCUM_CLEAR_VALUE", GLfloatN,55 [ "ctx->Accum.ClearColor[0]",56 "ctx->Accum.ClearColor[1]",57 "ctx->Accum.ClearColor[2]",58 "ctx->Accum.ClearColor[3]" ],59 "", None ),60 ( "GL_ALPHA_BIAS", GLfloat, ["ctx->Pixel.AlphaBias"], "", None ),61 ( "GL_ALPHA_BITS", GLint, ["ctx->DrawBuffer->Visual.alphaBits"],62 "", None ),63 ( "GL_ALPHA_SCALE", GLfloat, ["ctx->Pixel.AlphaScale"], "", None ),64 ( "GL_ALPHA_TEST", GLboolean, ["ctx->Color.AlphaEnabled"], "", None ),65 ( "GL_ALPHA_TEST_FUNC", GLenum, ["ctx->Color.AlphaFunc"], "", None ),66 ( "GL_ALPHA_TEST_REF", GLfloatN, ["ctx->Color.AlphaRef"], "", None ),67 ( "GL_ATTRIB_STACK_DEPTH", GLint, ["ctx->AttribStackDepth"], "", None ),68 ( "GL_AUTO_NORMAL", GLboolean, ["ctx->Eval.AutoNormal"], "", None ),69 ( "GL_AUX_BUFFERS", GLint, ["ctx->DrawBuffer->Visual.numAuxBuffers"],70 "", None ),71 ( "GL_BLEND", GLboolean, ["ctx->Color.BlendEnabled"], "", None ),72 ( "GL_BLEND_DST", GLenum, ["ctx->Color.BlendDstRGB"], "", None ),73 ( "GL_BLEND_SRC", GLenum, ["ctx->Color.BlendSrcRGB"], "", None ),74 ( "GL_BLEND_SRC_RGB_EXT", GLenum, ["ctx->Color.BlendSrcRGB"], "", None ),75 ( "GL_BLEND_DST_RGB_EXT", GLenum, ["ctx->Color.BlendDstRGB"], "", None ),76 ( "GL_BLEND_SRC_ALPHA_EXT", GLenum, ["ctx->Color.BlendSrcA"], "", None ),77 ( "GL_BLEND_DST_ALPHA_EXT", GLenum, ["ctx->Color.BlendDstA"], "", None ),78 ( "GL_BLEND_EQUATION", GLenum, ["ctx->Color.BlendEquationRGB "], "", None),79 ( "GL_BLEND_EQUATION_ALPHA_EXT", GLenum, ["ctx->Color.BlendEquationA "],80 "", None ),81 ( "GL_BLEND_COLOR_EXT", GLfloatN,82 [ "ctx->Color.BlendColor[0]",83 "ctx->Color.BlendColor[1]",84 "ctx->Color.BlendColor[2]",85 "ctx->Color.BlendColor[3]"], "", None ),86 ( "GL_BLUE_BIAS", GLfloat, ["ctx->Pixel.BlueBias"], "", None ),87 ( "GL_BLUE_BITS", GLint, ["ctx->DrawBuffer->Visual.blueBits"], "", None ),88 ( "GL_BLUE_SCALE", GLfloat, ["ctx->Pixel.BlueScale"], "", None ),89 ( "GL_CLIENT_ATTRIB_STACK_DEPTH", GLint,90 ["ctx->ClientAttribStackDepth"], "", None ),91 ( "GL_CLIP_PLANE0", GLboolean,92 [ "(ctx->Transform.ClipPlanesEnabled >> 0) & 1" ], "", None ),93 ( "GL_CLIP_PLANE1", GLboolean,94 [ "(ctx->Transform.ClipPlanesEnabled >> 1) & 1" ], "", None ),95 ( "GL_CLIP_PLANE2", GLboolean,96 [ "(ctx->Transform.ClipPlanesEnabled >> 2) & 1" ], "", None ),97 ( "GL_CLIP_PLANE3", GLboolean,98 [ "(ctx->Transform.ClipPlanesEnabled >> 3) & 1" ], "", None ),99 ( "GL_CLIP_PLANE4", GLboolean,100 [ "(ctx->Transform.ClipPlanesEnabled >> 4) & 1" ], "", None ),101 ( "GL_CLIP_PLANE5", GLboolean,102 [ "(ctx->Transform.ClipPlanesEnabled >> 5) & 1" ], "", None ),103 ( "GL_COLOR_CLEAR_VALUE", GLfloatN,104 [ "ctx->Color.ClearColor[0]",105 "ctx->Color.ClearColor[1]",106 "ctx->Color.ClearColor[2]",107 "ctx->Color.ClearColor[3]" ], "", None ),108 ( "GL_COLOR_MATERIAL", GLboolean,109 ["ctx->Light.ColorMaterialEnabled"], "", None ),110 ( "GL_COLOR_MATERIAL_FACE", GLenum,111 ["ctx->Light.ColorMaterialFace"], "", None ),112 ( "GL_COLOR_MATERIAL_PARAMETER", GLenum,113 ["ctx->Light.ColorMaterialMode"], "", None ),114 ( "GL_COLOR_WRITEMASK", GLint,115 [ "ctx->Color.ColorMask[RCOMP] ? 1 : 0",116 "ctx->Color.ColorMask[GCOMP] ? 1 : 0",117 "ctx->Color.ColorMask[BCOMP] ? 1 : 0",118 "ctx->Color.ColorMask[ACOMP] ? 1 : 0" ], "", None ),119 ( "GL_CULL_FACE", GLboolean, ["ctx->Polygon.CullFlag"], "", None ),120 ( "GL_CULL_FACE_MODE", GLenum, ["ctx->Polygon.CullFaceMode"], "", None ),121 ( "GL_CURRENT_COLOR", GLfloatN,122 [ "ctx->Current.Attrib[VERT_ATTRIB_COLOR0][0]",123 "ctx->Current.Attrib[VERT_ATTRIB_COLOR0][1]",124 "ctx->Current.Attrib[VERT_ATTRIB_COLOR0][2]",125 "ctx->Current.Attrib[VERT_ATTRIB_COLOR0][3]" ],126 "FLUSH_CURRENT(ctx, 0);", None ),127 ( "GL_CURRENT_INDEX", GLfloat,128 [ "ctx->Current.Attrib[VERT_ATTRIB_COLOR_INDEX][0]" ],129 "FLUSH_CURRENT(ctx, 0);", None ),130 ( "GL_CURRENT_NORMAL", GLfloatN,131 [ "ctx->Current.Attrib[VERT_ATTRIB_NORMAL][0]",132 "ctx->Current.Attrib[VERT_ATTRIB_NORMAL][1]",133 "ctx->Current.Attrib[VERT_ATTRIB_NORMAL][2]"],134 "FLUSH_CURRENT(ctx, 0);", None ),135 ( "GL_CURRENT_RASTER_COLOR", GLfloatN,136 ["ctx->Current.RasterColor[0]",137 "ctx->Current.RasterColor[1]",138 "ctx->Current.RasterColor[2]",139 "ctx->Current.RasterColor[3]"], "", None ),140 ( "GL_CURRENT_RASTER_DISTANCE", GLfloat,141 ["ctx->Current.RasterDistance"], "", None ),142 ( "GL_CURRENT_RASTER_INDEX", GLfloat,143 ["ctx->Current.RasterIndex"], "", None ),144 ( "GL_CURRENT_RASTER_POSITION", GLfloat,145 ["ctx->Current.RasterPos[0]",146 "ctx->Current.RasterPos[1]",147 "ctx->Current.RasterPos[2]",148 "ctx->Current.RasterPos[3]"], "", None ),149 ( "GL_CURRENT_RASTER_SECONDARY_COLOR", GLfloatN,150 ["ctx->Current.RasterSecondaryColor[0]",151 "ctx->Current.RasterSecondaryColor[1]",152 "ctx->Current.RasterSecondaryColor[2]",153 "ctx->Current.RasterSecondaryColor[3]"], "", None ),154 ( "GL_CURRENT_RASTER_TEXTURE_COORDS", GLfloat,155 ["ctx->Current.RasterTexCoords[texUnit][0]",156 "ctx->Current.RasterTexCoords[texUnit][1]",157 "ctx->Current.RasterTexCoords[texUnit][2]",158 "ctx->Current.RasterTexCoords[texUnit][3]"],159 "const GLuint texUnit = ctx->Texture.CurrentUnit;", None ),160 ( "GL_CURRENT_RASTER_POSITION_VALID", GLboolean,161 ["ctx->Current.RasterPosValid"], "", None ),162 ( "GL_CURRENT_TEXTURE_COORDS", GLfloat,163 ["ctx->Current.Attrib[VERT_ATTRIB_TEX0 + texUnit][0]",164 "ctx->Current.Attrib[VERT_ATTRIB_TEX0 + texUnit][1]",165 "ctx->Current.Attrib[VERT_ATTRIB_TEX0 + texUnit][2]",166 "ctx->Current.Attrib[VERT_ATTRIB_TEX0 + texUnit][3]"],167 "const GLuint texUnit = ctx->Texture.CurrentUnit;", None ),168 ( "GL_DEPTH_BIAS", GLfloat, ["ctx->Pixel.DepthBias"], "", None ),169 ( "GL_DEPTH_BITS", GLint, ["ctx->DrawBuffer->Visual.depthBits"],170 "", None ),171 ( "GL_DEPTH_CLEAR_VALUE", GLfloat, ["ctx->Depth.Clear"], "", None ),172 ( "GL_DEPTH_FUNC", GLenum, ["ctx->Depth.Func"], "", None ),173 ( "GL_DEPTH_RANGE", GLfloatN,174 [ "ctx->Viewport.Near", "ctx->Viewport.Far" ], "", None ),175 ( "GL_DEPTH_SCALE", GLfloat, ["ctx->Pixel.DepthScale"], "", None ),176 ( "GL_DEPTH_TEST", GLboolean, ["ctx->Depth.Test"], "", None ),177 ( "GL_DEPTH_WRITEMASK", GLboolean, ["ctx->Depth.Mask"], "", None ),178 ( "GL_DITHER", GLboolean, ["ctx->Color.DitherFlag"], "", None ),179 ( "GL_DOUBLEBUFFER", GLboolean,180 ["ctx->DrawBuffer->Visual.doubleBufferMode"], "", None ),181 ( "GL_DRAW_BUFFER", GLenum, ["ctx->DrawBuffer->ColorDrawBuffer[0]"], "", None ),182 ( "GL_EDGE_FLAG", GLboolean, ["(ctx->Current.Attrib[VERT_ATTRIB_EDGEFLAG][0] == 1.0)"],183 "FLUSH_CURRENT(ctx, 0);", None ),184 ( "GL_FEEDBACK_BUFFER_SIZE", GLint, ["ctx->Feedback.BufferSize"], "", None ),185 ( "GL_FEEDBACK_BUFFER_TYPE", GLenum, ["ctx->Feedback.Type"], "", None ),186 ( "GL_FOG", GLboolean, ["ctx->Fog.Enabled"], "", None ),187 ( "GL_FOG_COLOR", GLfloatN,188 [ "ctx->Fog.Color[0]",189 "ctx->Fog.Color[1]",190 "ctx->Fog.Color[2]",191 "ctx->Fog.Color[3]" ], "", None ),192 ( "GL_FOG_DENSITY", GLfloat, ["ctx->Fog.Density"], "", None ),193 ( "GL_FOG_END", GLfloat, ["ctx->Fog.End"], "", None ),194 ( "GL_FOG_HINT", GLenum, ["ctx->Hint.Fog"], "", None ),195 ( "GL_FOG_INDEX", GLfloat, ["ctx->Fog.Index"], "", None ),196 ( "GL_FOG_MODE", GLenum, ["ctx->Fog.Mode"], "", None ),197 ( "GL_FOG_START", GLfloat, ["ctx->Fog.Start"], "", None ),198 ( "GL_FRONT_FACE", GLenum, ["ctx->Polygon.FrontFace"], "", None ),199 ( "GL_GREEN_BIAS", GLfloat, ["ctx->Pixel.GreenBias"], "", None ),200 ( "GL_GREEN_BITS", GLint, ["ctx->DrawBuffer->Visual.greenBits"],201 "", None ),202 ( "GL_GREEN_SCALE", GLfloat, ["ctx->Pixel.GreenScale"], "", None ),203 ( "GL_INDEX_BITS", GLint, ["ctx->DrawBuffer->Visual.indexBits"],204 "", None ),205 ( "GL_INDEX_CLEAR_VALUE", GLint, ["ctx->Color.ClearIndex"], "", None ),206 ( "GL_INDEX_MODE", GLboolean, ["!ctx->DrawBuffer->Visual.rgbMode"],207 "", None ),208 ( "GL_INDEX_OFFSET", GLint, ["ctx->Pixel.IndexOffset"], "", None ),209 ( "GL_INDEX_SHIFT", GLint, ["ctx->Pixel.IndexShift"], "", None ),210 ( "GL_INDEX_WRITEMASK", GLint, ["ctx->Color.IndexMask"], "", None ),211 ( "GL_LIGHT0", GLboolean, ["ctx->Light.Light[0].Enabled"], "", None ),212 ( "GL_LIGHT1", GLboolean, ["ctx->Light.Light[1].Enabled"], "", None ),213 ( "GL_LIGHT2", GLboolean, ["ctx->Light.Light[2].Enabled"], "", None ),214 ( "GL_LIGHT3", GLboolean, ["ctx->Light.Light[3].Enabled"], "", None ),215 ( "GL_LIGHT4", GLboolean, ["ctx->Light.Light[4].Enabled"], "", None ),216 ( "GL_LIGHT5", GLboolean, ["ctx->Light.Light[5].Enabled"], "", None ),217 ( "GL_LIGHT6", GLboolean, ["ctx->Light.Light[6].Enabled"], "", None ),218 ( "GL_LIGHT7", GLboolean, ["ctx->Light.Light[7].Enabled"], "", None ),219 ( "GL_LIGHTING", GLboolean, ["ctx->Light.Enabled"], "", None ),220 ( "GL_LIGHT_MODEL_AMBIENT", GLfloatN,221 ["ctx->Light.Model.Ambient[0]",222 "ctx->Light.Model.Ambient[1]",223 "ctx->Light.Model.Ambient[2]",224 "ctx->Light.Model.Ambient[3]"], "", None ),225 ( "GL_LIGHT_MODEL_COLOR_CONTROL", GLenum,226 ["ctx->Light.Model.ColorControl"], "", None ),227 ( "GL_LIGHT_MODEL_LOCAL_VIEWER", GLboolean,228 ["ctx->Light.Model.LocalViewer"], "", None ),229 ( "GL_LIGHT_MODEL_TWO_SIDE", GLboolean, ["ctx->Light.Model.TwoSide"], "", None ),230 ( "GL_LINE_SMOOTH", GLboolean, ["ctx->Line.SmoothFlag"], "", None ),231 ( "GL_LINE_SMOOTH_HINT", GLenum, ["ctx->Hint.LineSmooth"], "", None ),232 ( "GL_LINE_STIPPLE", GLboolean, ["ctx->Line.StippleFlag"], "", None ),233 ( "GL_LINE_STIPPLE_PATTERN", GLint, ["ctx->Line.StipplePattern"], "", None ),234 ( "GL_LINE_STIPPLE_REPEAT", GLint, ["ctx->Line.StippleFactor"], "", None ),235 ( "GL_LINE_WIDTH", GLfloat, ["ctx->Line.Width"], "", None ),236 ( "GL_LINE_WIDTH_GRANULARITY", GLfloat,237 ["ctx->Const.LineWidthGranularity"], "", None ),238 ( "GL_LINE_WIDTH_RANGE", GLfloat,239 ["ctx->Const.MinLineWidthAA",240 "ctx->Const.MaxLineWidthAA"], "", None ),241 ( "GL_ALIASED_LINE_WIDTH_RANGE", GLfloat,242 ["ctx->Const.MinLineWidth",243 "ctx->Const.MaxLineWidth"], "", None ),244 ( "GL_LIST_BASE", GLint, ["ctx->List.ListBase"], "", None ),245 ( "GL_LIST_INDEX", GLint, ["ctx->ListState.CurrentListNum"], "", None ),246 ( "GL_LIST_MODE", GLenum, ["mode"],247 """GLenum mode;248 if (!ctx->CompileFlag)249 mode = 0;250 else if (ctx->ExecuteFlag)251 mode = GL_COMPILE_AND_EXECUTE;252 else253 mode = GL_COMPILE;""", None ),254 ( "GL_INDEX_LOGIC_OP", GLboolean, ["ctx->Color.IndexLogicOpEnabled"], "", None ),255 ( "GL_COLOR_LOGIC_OP", GLboolean, ["ctx->Color.ColorLogicOpEnabled"], "", None ),256 ( "GL_LOGIC_OP_MODE", GLenum, ["ctx->Color.LogicOp"], "", None ),257 ( "GL_MAP1_COLOR_4", GLboolean, ["ctx->Eval.Map1Color4"], "", None ),258 ( "GL_MAP1_GRID_DOMAIN", GLfloat,259 ["ctx->Eval.MapGrid1u1",260 "ctx->Eval.MapGrid1u2"], "", None ),261 ( "GL_MAP1_GRID_SEGMENTS", GLint, ["ctx->Eval.MapGrid1un"], "", None ),262 ( "GL_MAP1_INDEX", GLboolean, ["ctx->Eval.Map1Index"], "", None ),263 ( "GL_MAP1_NORMAL", GLboolean, ["ctx->Eval.Map1Normal"], "", None ),264 ( "GL_MAP1_TEXTURE_COORD_1", GLboolean, ["ctx->Eval.Map1TextureCoord1"], "", None ),265 ( "GL_MAP1_TEXTURE_COORD_2", GLboolean, ["ctx->Eval.Map1TextureCoord2"], "", None ),266 ( "GL_MAP1_TEXTURE_COORD_3", GLboolean, ["ctx->Eval.Map1TextureCoord3"], "", None ),267 ( "GL_MAP1_TEXTURE_COORD_4", GLboolean, ["ctx->Eval.Map1TextureCoord4"], "", None ),268 ( "GL_MAP1_VERTEX_3", GLboolean, ["ctx->Eval.Map1Vertex3"], "", None ),269 ( "GL_MAP1_VERTEX_4", GLboolean, ["ctx->Eval.Map1Vertex4"], "", None ),270 ( "GL_MAP2_COLOR_4", GLboolean, ["ctx->Eval.Map2Color4"], "", None ),271 ( "GL_MAP2_GRID_DOMAIN", GLfloat,272 ["ctx->Eval.MapGrid2u1",273 "ctx->Eval.MapGrid2u2",274 "ctx->Eval.MapGrid2v1",275 "ctx->Eval.MapGrid2v2"], "", None ),276 ( "GL_MAP2_GRID_SEGMENTS", GLint,277 ["ctx->Eval.MapGrid2un",278 "ctx->Eval.MapGrid2vn"], "", None ),279 ( "GL_MAP2_INDEX", GLboolean, ["ctx->Eval.Map2Index"], "", None ),280 ( "GL_MAP2_NORMAL", GLboolean, ["ctx->Eval.Map2Normal"], "", None ),281 ( "GL_MAP2_TEXTURE_COORD_1", GLboolean, ["ctx->Eval.Map2TextureCoord1"], "", None ),282 ( "GL_MAP2_TEXTURE_COORD_2", GLboolean, ["ctx->Eval.Map2TextureCoord2"], "", None ),283 ( "GL_MAP2_TEXTURE_COORD_3", GLboolean, ["ctx->Eval.Map2TextureCoord3"], "", None ),284 ( "GL_MAP2_TEXTURE_COORD_4", GLboolean, ["ctx->Eval.Map2TextureCoord4"], "", None ),285 ( "GL_MAP2_VERTEX_3", GLboolean, ["ctx->Eval.Map2Vertex3"], "", None ),286 ( "GL_MAP2_VERTEX_4", GLboolean, ["ctx->Eval.Map2Vertex4"], "", None ),287 ( "GL_MAP_COLOR", GLboolean, ["ctx->Pixel.MapColorFlag"], "", None ),288 ( "GL_MAP_STENCIL", GLboolean, ["ctx->Pixel.MapStencilFlag"], "", None ),289 ( "GL_MATRIX_MODE", GLenum, ["ctx->Transform.MatrixMode"], "", None ),290 ( "GL_MAX_ATTRIB_STACK_DEPTH", GLint, ["MAX_ATTRIB_STACK_DEPTH"], "", None ),291 ( "GL_MAX_CLIENT_ATTRIB_STACK_DEPTH", GLint, ["MAX_CLIENT_ATTRIB_STACK_DEPTH"], "", None ),292 ( "GL_MAX_CLIP_PLANES", GLint, ["ctx->Const.MaxClipPlanes"], "", None ),293 ( "GL_MAX_ELEMENTS_VERTICES", GLint, ["ctx->Const.MaxArrayLockSize"], "", None ),294 ( "GL_MAX_ELEMENTS_INDICES", GLint, ["ctx->Const.MaxArrayLockSize"], "", None ),295 ( "GL_MAX_EVAL_ORDER", GLint, ["MAX_EVAL_ORDER"], "", None ),296 ( "GL_MAX_LIGHTS", GLint, ["ctx->Const.MaxLights"], "", None ),297 ( "GL_MAX_LIST_NESTING", GLint, ["MAX_LIST_NESTING"], "", None ),298 ( "GL_MAX_MODELVIEW_STACK_DEPTH", GLint, ["MAX_MODELVIEW_STACK_DEPTH"], "", None ),299 ( "GL_MAX_NAME_STACK_DEPTH", GLint, ["MAX_NAME_STACK_DEPTH"], "", None ),300 ( "GL_MAX_PIXEL_MAP_TABLE", GLint, ["MAX_PIXEL_MAP_TABLE"], "", None ),301 ( "GL_MAX_PROJECTION_STACK_DEPTH", GLint, ["MAX_PROJECTION_STACK_DEPTH"], "", None ),302 ( "GL_MAX_TEXTURE_SIZE", GLint, ["1 << (ctx->Const.MaxTextureLevels - 1)"], "", None ),303 ( "GL_MAX_3D_TEXTURE_SIZE", GLint, ["1 << (ctx->Const.Max3DTextureLevels - 1)"], "", None ),304 ( "GL_MAX_TEXTURE_STACK_DEPTH", GLint, ["MAX_TEXTURE_STACK_DEPTH"], "", None ),305 ( "GL_MAX_VIEWPORT_DIMS", GLint,306 ["ctx->Const.MaxViewportWidth", "ctx->Const.MaxViewportHeight"],307 "", None ),308 ( "GL_MODELVIEW_MATRIX", GLfloat,309 [ "matrix[0]", "matrix[1]", "matrix[2]", "matrix[3]",310 "matrix[4]", "matrix[5]", "matrix[6]", "matrix[7]",311 "matrix[8]", "matrix[9]", "matrix[10]", "matrix[11]",312 "matrix[12]", "matrix[13]", "matrix[14]", "matrix[15]" ],313 "const GLfloat *matrix = ctx->ModelviewMatrixStack.Top->m;", None ),314 ( "GL_MODELVIEW_STACK_DEPTH", GLint, ["ctx->ModelviewMatrixStack.Depth + 1"], "", None ),315 ( "GL_NAME_STACK_DEPTH", GLint, ["ctx->Select.NameStackDepth"], "", None ),316 ( "GL_NORMALIZE", GLboolean, ["ctx->Transform.Normalize"], "", None ),317 ( "GL_PACK_ALIGNMENT", GLint, ["ctx->Pack.Alignment"], "", None ),318 ( "GL_PACK_LSB_FIRST", GLboolean, ["ctx->Pack.LsbFirst"], "", None ),319 ( "GL_PACK_ROW_LENGTH", GLint, ["ctx->Pack.RowLength"], "", None ),320 ( "GL_PACK_SKIP_PIXELS", GLint, ["ctx->Pack.SkipPixels"], "", None ),321 ( "GL_PACK_SKIP_ROWS", GLint, ["ctx->Pack.SkipRows"], "", None ),322 ( "GL_PACK_SWAP_BYTES", GLboolean, ["ctx->Pack.SwapBytes"], "", None ),323 ( "GL_PACK_SKIP_IMAGES_EXT", GLint, ["ctx->Pack.SkipImages"], "", None ),324 ( "GL_PACK_IMAGE_HEIGHT_EXT", GLint, ["ctx->Pack.ImageHeight"], "", None ),325 ( "GL_PACK_INVERT_MESA", GLboolean, ["ctx->Pack.Invert"], "", None ),326 ( "GL_PERSPECTIVE_CORRECTION_HINT", GLenum,327 ["ctx->Hint.PerspectiveCorrection"], "", None ),328 ( "GL_PIXEL_MAP_A_TO_A_SIZE", GLint, ["ctx->PixelMaps.AtoA.Size"], "", None ),329 ( "GL_PIXEL_MAP_B_TO_B_SIZE", GLint, ["ctx->PixelMaps.BtoB.Size"], "", None ),330 ( "GL_PIXEL_MAP_G_TO_G_SIZE", GLint, ["ctx->PixelMaps.GtoG.Size"], "", None ),331 ( "GL_PIXEL_MAP_I_TO_A_SIZE", GLint, ["ctx->PixelMaps.ItoA.Size"], "", None ),332 ( "GL_PIXEL_MAP_I_TO_B_SIZE", GLint, ["ctx->PixelMaps.ItoB.Size"], "", None ),333 ( "GL_PIXEL_MAP_I_TO_G_SIZE", GLint, ["ctx->PixelMaps.ItoG.Size"], "", None ),334 ( "GL_PIXEL_MAP_I_TO_I_SIZE", GLint, ["ctx->PixelMaps.ItoI.Size"], "", None ),335 ( "GL_PIXEL_MAP_I_TO_R_SIZE", GLint, ["ctx->PixelMaps.ItoR.Size"], "", None ),336 ( "GL_PIXEL_MAP_R_TO_R_SIZE", GLint, ["ctx->PixelMaps.RtoR.Size"], "", None ),337 ( "GL_PIXEL_MAP_S_TO_S_SIZE", GLint, ["ctx->PixelMaps.StoS.Size"], "", None ),338 ( "GL_POINT_SIZE", GLfloat, ["ctx->Point.Size"], "", None ),339 ( "GL_POINT_SIZE_GRANULARITY", GLfloat,340 ["ctx->Const.PointSizeGranularity"], "", None ),341 ( "GL_POINT_SIZE_RANGE", GLfloat,342 ["ctx->Const.MinPointSizeAA",343 "ctx->Const.MaxPointSizeAA"], "", None ),344 ( "GL_ALIASED_POINT_SIZE_RANGE", GLfloat,345 ["ctx->Const.MinPointSize",346 "ctx->Const.MaxPointSize"], "", None ),347 ( "GL_POINT_SMOOTH", GLboolean, ["ctx->Point.SmoothFlag"], "", None ),348 ( "GL_POINT_SMOOTH_HINT", GLenum, ["ctx->Hint.PointSmooth"], "", None ),349 ( "GL_POINT_SIZE_MIN_EXT", GLfloat, ["ctx->Point.MinSize"], "", None ),350 ( "GL_POINT_SIZE_MAX_EXT", GLfloat, ["ctx->Point.MaxSize"], "", None ),351 ( "GL_POINT_FADE_THRESHOLD_SIZE_EXT", GLfloat,352 ["ctx->Point.Threshold"], "", None ),353 ( "GL_DISTANCE_ATTENUATION_EXT", GLfloat,354 ["ctx->Point.Params[0]",355 "ctx->Point.Params[1]",356 "ctx->Point.Params[2]"], "", None ),357 ( "GL_POLYGON_MODE", GLenum,358 ["ctx->Polygon.FrontMode",359 "ctx->Polygon.BackMode"], "", None ),360 ( "GL_POLYGON_OFFSET_BIAS_EXT", GLfloat, ["ctx->Polygon.OffsetUnits"], "", None ),361 ( "GL_POLYGON_OFFSET_FACTOR", GLfloat, ["ctx->Polygon.OffsetFactor "], "", None ),362 ( "GL_POLYGON_OFFSET_UNITS", GLfloat, ["ctx->Polygon.OffsetUnits "], "", None ),363 ( "GL_POLYGON_SMOOTH", GLboolean, ["ctx->Polygon.SmoothFlag"], "", None ),364 ( "GL_POLYGON_SMOOTH_HINT", GLenum, ["ctx->Hint.PolygonSmooth"], "", None ),365 ( "GL_POLYGON_STIPPLE", GLboolean, ["ctx->Polygon.StippleFlag"], "", None ),366 ( "GL_PROJECTION_MATRIX", GLfloat,367 [ "matrix[0]", "matrix[1]", "matrix[2]", "matrix[3]",368 "matrix[4]", "matrix[5]", "matrix[6]", "matrix[7]",369 "matrix[8]", "matrix[9]", "matrix[10]", "matrix[11]",370 "matrix[12]", "matrix[13]", "matrix[14]", "matrix[15]" ],371 "const GLfloat *matrix = ctx->ProjectionMatrixStack.Top->m;", None ),372 ( "GL_PROJECTION_STACK_DEPTH", GLint,373 ["ctx->ProjectionMatrixStack.Depth + 1"], "", None ),374 ( "GL_READ_BUFFER", GLenum, ["ctx->ReadBuffer->ColorReadBuffer"], "", None ),375 ( "GL_RED_BIAS", GLfloat, ["ctx->Pixel.RedBias"], "", None ),376 ( "GL_RED_BITS", GLint, ["ctx->DrawBuffer->Visual.redBits"], "", None ),377 ( "GL_RED_SCALE", GLfloat, ["ctx->Pixel.RedScale"], "", None ),378 ( "GL_RENDER_MODE", GLenum, ["ctx->RenderMode"], "", None ),379 ( "GL_RESCALE_NORMAL", GLboolean,380 ["ctx->Transform.RescaleNormals"], "", None ),381 ( "GL_RGBA_MODE", GLboolean, ["ctx->DrawBuffer->Visual.rgbMode"],382 "", None ),383 ( "GL_SCISSOR_BOX", GLint,384 ["ctx->Scissor.X",385 "ctx->Scissor.Y",386 "ctx->Scissor.Width",387 "ctx->Scissor.Height"], "", None ),388 ( "GL_SCISSOR_TEST", GLboolean, ["ctx->Scissor.Enabled"], "", None ),389 ( "GL_SELECTION_BUFFER_SIZE", GLint, ["ctx->Select.BufferSize"], "", None ),390 ( "GL_SHADE_MODEL", GLenum, ["ctx->Light.ShadeModel"], "", None ),391 ( "GL_SHARED_TEXTURE_PALETTE_EXT", GLboolean,392 ["ctx->Texture.SharedPalette"], "", None ),393 ( "GL_STENCIL_BITS", GLint, ["ctx->DrawBuffer->Visual.stencilBits"], "", None ),394 ( "GL_STENCIL_CLEAR_VALUE", GLint, ["ctx->Stencil.Clear"], "", None ),395 ( "GL_STENCIL_FAIL", GLenum,396 ["ctx->Stencil.FailFunc[ctx->Stencil.ActiveFace]"], "", None ),397 ( "GL_STENCIL_FUNC", GLenum,398 ["ctx->Stencil.Function[ctx->Stencil.ActiveFace]"], "", None ),399 ( "GL_STENCIL_PASS_DEPTH_FAIL", GLenum,400 ["ctx->Stencil.ZFailFunc[ctx->Stencil.ActiveFace]"], "", None ),401 ( "GL_STENCIL_PASS_DEPTH_PASS", GLenum,402 ["ctx->Stencil.ZPassFunc[ctx->Stencil.ActiveFace]"], "", None ),403 ( "GL_STENCIL_REF", GLint,404 ["ctx->Stencil.Ref[ctx->Stencil.ActiveFace]"], "", None ),405 ( "GL_STENCIL_TEST", GLboolean, ["ctx->Stencil.Enabled"], "", None ),406 ( "GL_STENCIL_VALUE_MASK", GLint,407 ["ctx->Stencil.ValueMask[ctx->Stencil.ActiveFace]"], "", None ),408 ( "GL_STENCIL_WRITEMASK", GLint,409 ["ctx->Stencil.WriteMask[ctx->Stencil.ActiveFace]"], "", None ),410 ( "GL_STEREO", GLboolean, ["ctx->DrawBuffer->Visual.stereoMode"],411 "", None ),412 ( "GL_SUBPIXEL_BITS", GLint, ["ctx->Const.SubPixelBits"], "", None ),413 ( "GL_TEXTURE_1D", GLboolean, ["_mesa_IsEnabled(GL_TEXTURE_1D)"], "", None ),414 ( "GL_TEXTURE_2D", GLboolean, ["_mesa_IsEnabled(GL_TEXTURE_2D)"], "", None ),415 ( "GL_TEXTURE_3D", GLboolean, ["_mesa_IsEnabled(GL_TEXTURE_3D)"], "", None ),416 ( "GL_TEXTURE_BINDING_1D", GLint,417 ["ctx->Texture.Unit[ctx->Texture.CurrentUnit].Current1D->Name"], "", None ),418 ( "GL_TEXTURE_BINDING_2D", GLint,419 ["ctx->Texture.Unit[ctx->Texture.CurrentUnit].Current2D->Name"], "", None ),420 ( "GL_TEXTURE_BINDING_3D", GLint,421 ["ctx->Texture.Unit[ctx->Texture.CurrentUnit].Current3D->Name"], "", None ),422 ( "GL_TEXTURE_ENV_COLOR", GLfloatN,423 ["color[0]", "color[1]", "color[2]", "color[3]"],424 "const GLfloat *color = ctx->Texture.Unit[ctx->Texture.CurrentUnit].EnvColor;",425 None ),426 ( "GL_TEXTURE_ENV_MODE", GLenum,427 ["ctx->Texture.Unit[ctx->Texture.CurrentUnit].EnvMode"], "", None ),428 ( "GL_TEXTURE_GEN_S", GLboolean,429 ["((ctx->Texture.Unit[ctx->Texture.CurrentUnit].TexGenEnabled & S_BIT) ? 1 : 0)"], "", None ),430 ( "GL_TEXTURE_GEN_T", GLboolean,431 ["((ctx->Texture.Unit[ctx->Texture.CurrentUnit].TexGenEnabled & T_BIT) ? 1 : 0)"], "", None ),432 ( "GL_TEXTURE_GEN_R", GLboolean,433 ["((ctx->Texture.Unit[ctx->Texture.CurrentUnit].TexGenEnabled & R_BIT) ? 1 : 0)"], "", None ),434 ( "GL_TEXTURE_GEN_Q", GLboolean,435 ["((ctx->Texture.Unit[ctx->Texture.CurrentUnit].TexGenEnabled & Q_BIT) ? 1 : 0)"], "", None ),436 ( "GL_TEXTURE_MATRIX", GLfloat,437 ["matrix[0]", "matrix[1]", "matrix[2]", "matrix[3]",438 "matrix[4]", "matrix[5]", "matrix[6]", "matrix[7]",439 "matrix[8]", "matrix[9]", "matrix[10]", "matrix[11]",440 "matrix[12]", "matrix[13]", "matrix[14]", "matrix[15]" ],441 "const GLfloat *matrix = ctx->TextureMatrixStack[ctx->Texture.CurrentUnit].Top->m;", None ),442 ( "GL_TEXTURE_STACK_DEPTH", GLint,443 ["ctx->TextureMatrixStack[ctx->Texture.CurrentUnit].Depth + 1"], "", None ),444 ( "GL_UNPACK_ALIGNMENT", GLint, ["ctx->Unpack.Alignment"], "", None ),445 ( "GL_UNPACK_LSB_FIRST", GLboolean, ["ctx->Unpack.LsbFirst"], "", None ),446 ( "GL_UNPACK_ROW_LENGTH", GLint, ["ctx->Unpack.RowLength"], "", None ),447 ( "GL_UNPACK_SKIP_PIXELS", GLint, ["ctx->Unpack.SkipPixels"], "", None ),448 ( "GL_UNPACK_SKIP_ROWS", GLint, ["ctx->Unpack.SkipRows"], "", None ),449 ( "GL_UNPACK_SWAP_BYTES", GLboolean, ["ctx->Unpack.SwapBytes"], "", None ),450 ( "GL_UNPACK_SKIP_IMAGES_EXT", GLint, ["ctx->Unpack.SkipImages"], "", None ),451 ( "GL_UNPACK_IMAGE_HEIGHT_EXT", GLint, ["ctx->Unpack.ImageHeight"], "", None ),452 ( "GL_UNPACK_CLIENT_STORAGE_APPLE", GLboolean, ["ctx->Unpack.ClientStorage"], "", None ),453 ( "GL_VIEWPORT", GLint, [ "ctx->Viewport.X", "ctx->Viewport.Y",454 "ctx->Viewport.Width", "ctx->Viewport.Height" ], "", None ),455 ( "GL_ZOOM_X", GLfloat, ["ctx->Pixel.ZoomX"], "", None ),456 ( "GL_ZOOM_Y", GLfloat, ["ctx->Pixel.ZoomY"], "", None ),457 # Vertex arrays458 ( "GL_VERTEX_ARRAY", GLboolean, ["ctx->Array.ArrayObj->Vertex.Enabled"], "", None ),459 ( "GL_VERTEX_ARRAY_SIZE", GLint, ["ctx->Array.ArrayObj->Vertex.Size"], "", None ),460 ( "GL_VERTEX_ARRAY_TYPE", GLenum, ["ctx->Array.ArrayObj->Vertex.Type"], "", None ),461 ( "GL_VERTEX_ARRAY_STRIDE", GLint, ["ctx->Array.ArrayObj->Vertex.Stride"], "", None ),462 ( "GL_VERTEX_ARRAY_COUNT_EXT", GLint, ["0"], "", None ),463 ( "GL_NORMAL_ARRAY", GLenum, ["ctx->Array.ArrayObj->Normal.Enabled"], "", None ),464 ( "GL_NORMAL_ARRAY_TYPE", GLenum, ["ctx->Array.ArrayObj->Normal.Type"], "", None ),465 ( "GL_NORMAL_ARRAY_STRIDE", GLint, ["ctx->Array.ArrayObj->Normal.Stride"], "", None ),466 ( "GL_NORMAL_ARRAY_COUNT_EXT", GLint, ["0"], "", None ),467 ( "GL_COLOR_ARRAY", GLboolean, ["ctx->Array.ArrayObj->Color.Enabled"], "", None ),468 ( "GL_COLOR_ARRAY_SIZE", GLint, ["ctx->Array.ArrayObj->Color.Size"], "", None ),469 ( "GL_COLOR_ARRAY_TYPE", GLenum, ["ctx->Array.ArrayObj->Color.Type"], "", None ),470 ( "GL_COLOR_ARRAY_STRIDE", GLint, ["ctx->Array.ArrayObj->Color.Stride"], "", None ),471 ( "GL_COLOR_ARRAY_COUNT_EXT", GLint, ["0"], "", None ),472 ( "GL_INDEX_ARRAY", GLboolean, ["ctx->Array.ArrayObj->Index.Enabled"], "", None ),473 ( "GL_INDEX_ARRAY_TYPE", GLenum, ["ctx->Array.ArrayObj->Index.Type"], "", None ),474 ( "GL_INDEX_ARRAY_STRIDE", GLint, ["ctx->Array.ArrayObj->Index.Stride"], "", None ),475 ( "GL_INDEX_ARRAY_COUNT_EXT", GLint, ["0"], "", None ),476 ( "GL_TEXTURE_COORD_ARRAY", GLboolean,477 ["ctx->Array.ArrayObj->TexCoord[ctx->Array.ActiveTexture].Enabled"], "", None ),478 ( "GL_TEXTURE_COORD_ARRAY_SIZE", GLint,479 ["ctx->Array.ArrayObj->TexCoord[ctx->Array.ActiveTexture].Size"], "", None ),480 ( "GL_TEXTURE_COORD_ARRAY_TYPE", GLenum,481 ["ctx->Array.ArrayObj->TexCoord[ctx->Array.ActiveTexture].Type"], "", None ),482 ( "GL_TEXTURE_COORD_ARRAY_STRIDE", GLint,483 ["ctx->Array.ArrayObj->TexCoord[ctx->Array.ActiveTexture].Stride"], "", None ),484 ( "GL_TEXTURE_COORD_ARRAY_COUNT_EXT", GLint, ["0"], "", None ),485 ( "GL_EDGE_FLAG_ARRAY", GLboolean, ["ctx->Array.ArrayObj->EdgeFlag.Enabled"], "", None ),486 ( "GL_EDGE_FLAG_ARRAY_STRIDE", GLint, ["ctx->Array.ArrayObj->EdgeFlag.Stride"], "", None ),487 ( "GL_EDGE_FLAG_ARRAY_COUNT_EXT", GLint, ["0"], "", None ),488 # GL_ARB_multitexture489 ( "GL_MAX_TEXTURE_UNITS_ARB", GLint,490 ["ctx->Const.MaxTextureUnits"], "", ["ARB_multitexture"] ),491 ( "GL_ACTIVE_TEXTURE_ARB", GLint,492 [ "GL_TEXTURE0_ARB + ctx->Texture.CurrentUnit"], "", ["ARB_multitexture"] ),493 ( "GL_CLIENT_ACTIVE_TEXTURE_ARB", GLint,494 ["GL_TEXTURE0_ARB + ctx->Array.ActiveTexture"], "", ["ARB_multitexture"] ),495 # GL_ARB_texture_cube_map496 ( "GL_TEXTURE_CUBE_MAP_ARB", GLboolean,497 ["_mesa_IsEnabled(GL_TEXTURE_CUBE_MAP_ARB)"], "", ["ARB_texture_cube_map"] ),498 ( "GL_TEXTURE_BINDING_CUBE_MAP_ARB", GLint,499 ["ctx->Texture.Unit[ctx->Texture.CurrentUnit].CurrentCubeMap->Name"],500 "", ["ARB_texture_cube_map"] ),501 ( "GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB", GLint,502 ["(1 << (ctx->Const.MaxCubeTextureLevels - 1))"],503 "", ["ARB_texture_cube_map"]),504 # GL_ARB_texture_compression */505 ( "GL_TEXTURE_COMPRESSION_HINT_ARB", GLint,506 ["ctx->Hint.TextureCompression"], "", ["ARB_texture_compression"] ),507 ( "GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB", GLint,508 ["_mesa_get_compressed_formats(ctx, NULL, GL_FALSE)"],509 "", ["ARB_texture_compression"] ),510 ( "GL_COMPRESSED_TEXTURE_FORMATS_ARB", GLenum,511 [],512 """GLint formats[100];513 GLuint i, n = _mesa_get_compressed_formats(ctx, formats, GL_FALSE);514 ASSERT(n <= 100);515 for (i = 0; i < n; i++)516 params[i] = ENUM_TO_INT(formats[i]);""",517 ["ARB_texture_compression"] ),518 # GL_EXT_compiled_vertex_array519 ( "GL_ARRAY_ELEMENT_LOCK_FIRST_EXT", GLint, ["ctx->Array.LockFirst"],520 "", ["EXT_compiled_vertex_array"] ),521 ( "GL_ARRAY_ELEMENT_LOCK_COUNT_EXT", GLint, ["ctx->Array.LockCount"],522 "", ["EXT_compiled_vertex_array"] ),523 # GL_ARB_transpose_matrix524 ( "GL_TRANSPOSE_COLOR_MATRIX_ARB", GLfloat,525 ["matrix[0]", "matrix[4]", "matrix[8]", "matrix[12]",526 "matrix[1]", "matrix[5]", "matrix[9]", "matrix[13]",527 "matrix[2]", "matrix[6]", "matrix[10]", "matrix[14]",528 "matrix[3]", "matrix[7]", "matrix[11]", "matrix[15]"],529 "const GLfloat *matrix = ctx->ColorMatrixStack.Top->m;", None ),530 ( "GL_TRANSPOSE_MODELVIEW_MATRIX_ARB", GLfloat,531 ["matrix[0]", "matrix[4]", "matrix[8]", "matrix[12]",532 "matrix[1]", "matrix[5]", "matrix[9]", "matrix[13]",533 "matrix[2]", "matrix[6]", "matrix[10]", "matrix[14]",534 "matrix[3]", "matrix[7]", "matrix[11]", "matrix[15]"],535 "const GLfloat *matrix = ctx->ModelviewMatrixStack.Top->m;", None ),536 ( "GL_TRANSPOSE_PROJECTION_MATRIX_ARB", GLfloat,537 ["matrix[0]", "matrix[4]", "matrix[8]", "matrix[12]",538 "matrix[1]", "matrix[5]", "matrix[9]", "matrix[13]",539 "matrix[2]", "matrix[6]", "matrix[10]", "matrix[14]",540 "matrix[3]", "matrix[7]", "matrix[11]", "matrix[15]"],541 "const GLfloat *matrix = ctx->ProjectionMatrixStack.Top->m;", None ),542 ( "GL_TRANSPOSE_TEXTURE_MATRIX_ARB", GLfloat,543 ["matrix[0]", "matrix[4]", "matrix[8]", "matrix[12]",544 "matrix[1]", "matrix[5]", "matrix[9]", "matrix[13]",545 "matrix[2]", "matrix[6]", "matrix[10]", "matrix[14]",546 "matrix[3]", "matrix[7]", "matrix[11]", "matrix[15]"],547 "const GLfloat *matrix = ctx->TextureMatrixStack[ctx->Texture.CurrentUnit].Top->m;", None ),548 # GL_SGI_color_matrix (also in 1.2 imaging)549 ( "GL_COLOR_MATRIX_SGI", GLfloat,550 ["matrix[0]", "matrix[1]", "matrix[2]", "matrix[3]",551 "matrix[4]", "matrix[5]", "matrix[6]", "matrix[7]",552 "matrix[8]", "matrix[9]", "matrix[10]", "matrix[11]",553 "matrix[12]", "matrix[13]", "matrix[14]", "matrix[15]" ],554 "const GLfloat *matrix = ctx->ColorMatrixStack.Top->m;", None ),555 ( "GL_COLOR_MATRIX_STACK_DEPTH_SGI", GLint,556 ["ctx->ColorMatrixStack.Depth + 1"], "", None ),557 ( "GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI", GLint,558 ["MAX_COLOR_STACK_DEPTH"], "", None ),559 ( "GL_POST_COLOR_MATRIX_RED_SCALE_SGI", GLfloat,560 ["ctx->Pixel.PostColorMatrixScale[0]"], "", None ),561 ( "GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI", GLfloat,562 ["ctx->Pixel.PostColorMatrixScale[1]"], "", None ),563 ( "GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI", GLfloat,564 ["ctx->Pixel.PostColorMatrixScale[2]"], "", None ),565 ( "GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI", GLfloat,566 ["ctx->Pixel.PostColorMatrixScale[3]"], "", None ),567 ( "GL_POST_COLOR_MATRIX_RED_BIAS_SGI", GLfloat,568 ["ctx->Pixel.PostColorMatrixBias[0]"], "", None ),569 ( "GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI", GLfloat,570 ["ctx->Pixel.PostColorMatrixBias[1]"], "", None ),571 ( "GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI", GLfloat,572 ["ctx->Pixel.PostColorMatrixBias[2]"], "", None ),573 ( "GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI", GLfloat,574 ["ctx->Pixel.PostColorMatrixBias[3]"], "", None ),575 # GL_EXT_convolution (also in 1.2 imaging)576 ( "GL_CONVOLUTION_1D_EXT", GLboolean,577 ["ctx->Pixel.Convolution1DEnabled"], "", ["EXT_convolution"] ),578 ( "GL_CONVOLUTION_2D_EXT", GLboolean,579 ["ctx->Pixel.Convolution2DEnabled"], "", ["EXT_convolution"] ),580 ( "GL_SEPARABLE_2D_EXT", GLboolean,581 ["ctx->Pixel.Separable2DEnabled"], "", ["EXT_convolution"] ),582 ( "GL_POST_CONVOLUTION_RED_SCALE_EXT", GLfloat,583 ["ctx->Pixel.PostConvolutionScale[0]"], "", ["EXT_convolution"] ),584 ( "GL_POST_CONVOLUTION_GREEN_SCALE_EXT", GLfloat,585 ["ctx->Pixel.PostConvolutionScale[1]"], "", ["EXT_convolution"] ),586 ( "GL_POST_CONVOLUTION_BLUE_SCALE_EXT", GLfloat,587 ["ctx->Pixel.PostConvolutionScale[2]"], "", ["EXT_convolution"] ),588 ( "GL_POST_CONVOLUTION_ALPHA_SCALE_EXT", GLfloat,589 ["ctx->Pixel.PostConvolutionScale[3]"], "", ["EXT_convolution"] ),590 ( "GL_POST_CONVOLUTION_RED_BIAS_EXT", GLfloat,591 ["ctx->Pixel.PostConvolutionBias[0]"], "", ["EXT_convolution"] ),592 ( "GL_POST_CONVOLUTION_GREEN_BIAS_EXT", GLfloat,593 ["ctx->Pixel.PostConvolutionBias[1]"], "", ["EXT_convolution"] ),594 ( "GL_POST_CONVOLUTION_BLUE_BIAS_EXT", GLfloat,595 ["ctx->Pixel.PostConvolutionBias[2]"], "", ["EXT_convolution"] ),596 ( "GL_POST_CONVOLUTION_ALPHA_BIAS_EXT", GLfloat,597 ["ctx->Pixel.PostConvolutionBias[3]"], "", ["EXT_convolution"] ),598 # GL_EXT_histogram / GL_ARB_imaging599 ( "GL_HISTOGRAM", GLboolean,600 [ "ctx->Pixel.HistogramEnabled" ], "", ["EXT_histogram"] ),601 ( "GL_MINMAX", GLboolean,602 [ "ctx->Pixel.MinMaxEnabled" ], "", ["EXT_histogram"] ),603 # GL_SGI_color_table / GL_ARB_imaging604 ( "GL_COLOR_TABLE_SGI", GLboolean,605 ["ctx->Pixel.ColorTableEnabled[COLORTABLE_PRECONVOLUTION]"], "", ["SGI_color_table"] ),606 ( "GL_POST_CONVOLUTION_COLOR_TABLE_SGI", GLboolean,607 ["ctx->Pixel.ColorTableEnabled[COLORTABLE_POSTCONVOLUTION]"], "", ["SGI_color_table"] ),608 ( "GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI", GLboolean,609 ["ctx->Pixel.ColorTableEnabled[COLORTABLE_POSTCOLORMATRIX]"], "", ["SGI_color_table"] ),610 # GL_SGI_texture_color_table611 ( "GL_TEXTURE_COLOR_TABLE_SGI", GLboolean,612 ["ctx->Texture.Unit[ctx->Texture.CurrentUnit].ColorTableEnabled"],613 "", ["SGI_texture_color_table"] ),614 # GL_EXT_secondary_color615 ( "GL_COLOR_SUM_EXT", GLboolean,616 ["ctx->Fog.ColorSumEnabled"], "",617 ["EXT_secondary_color", "ARB_vertex_program"] ),618 ( "GL_CURRENT_SECONDARY_COLOR_EXT", GLfloatN,619 ["ctx->Current.Attrib[VERT_ATTRIB_COLOR1][0]",620 "ctx->Current.Attrib[VERT_ATTRIB_COLOR1][1]",621 "ctx->Current.Attrib[VERT_ATTRIB_COLOR1][2]",622 "ctx->Current.Attrib[VERT_ATTRIB_COLOR1][3]"],623 "FLUSH_CURRENT(ctx, 0);", ["EXT_secondary_color"] ),624 ( "GL_SECONDARY_COLOR_ARRAY_EXT", GLboolean,625 ["ctx->Array.ArrayObj->SecondaryColor.Enabled"], "", ["EXT_secondary_color"] ),626 ( "GL_SECONDARY_COLOR_ARRAY_TYPE_EXT", GLenum,627 ["ctx->Array.ArrayObj->SecondaryColor.Type"], "", ["EXT_secondary_color"] ),628 ( "GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT", GLint,629 ["ctx->Array.ArrayObj->SecondaryColor.Stride"], "", ["EXT_secondary_color"] ),630 ( "GL_SECONDARY_COLOR_ARRAY_SIZE_EXT", GLint,631 ["ctx->Array.ArrayObj->SecondaryColor.Size"], "", ["EXT_secondary_color"] ),632 # GL_EXT_fog_coord633 ( "GL_CURRENT_FOG_COORDINATE_EXT", GLfloat,634 ["ctx->Current.Attrib[VERT_ATTRIB_FOG][0]"],635 "FLUSH_CURRENT(ctx, 0);", ["EXT_fog_coord"] ),636 ( "GL_FOG_COORDINATE_ARRAY_EXT", GLboolean, ["ctx->Array.ArrayObj->FogCoord.Enabled"],637 "", ["EXT_fog_coord"] ),638 ( "GL_FOG_COORDINATE_ARRAY_TYPE_EXT", GLenum, ["ctx->Array.ArrayObj->FogCoord.Type"],639 "", ["EXT_fog_coord"] ),640 ( "GL_FOG_COORDINATE_ARRAY_STRIDE_EXT", GLint, ["ctx->Array.ArrayObj->FogCoord.Stride"],641 "", ["EXT_fog_coord"] ),642 ( "GL_FOG_COORDINATE_SOURCE_EXT", GLenum, ["ctx->Fog.FogCoordinateSource"],643 "", ["EXT_fog_coord"] ),644 # GL_EXT_texture_lod_bias645 ( "GL_MAX_TEXTURE_LOD_BIAS_EXT", GLfloat,646 ["ctx->Const.MaxTextureLodBias"], "", ["EXT_texture_lod_bias"]),647 # GL_EXT_texture_filter_anisotropic648 ( "GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT", GLfloat,649 ["ctx->Const.MaxTextureMaxAnisotropy"], "", ["EXT_texture_filter_anisotropic"]),650 # GL_ARB_multisample651 ( "GL_MULTISAMPLE_ARB", GLboolean,652 ["ctx->Multisample.Enabled"], "", ["ARB_multisample"] ),653 ( "GL_SAMPLE_ALPHA_TO_COVERAGE_ARB", GLboolean,654 ["ctx->Multisample.SampleAlphaToCoverage"], "", ["ARB_multisample"] ),655 ( "GL_SAMPLE_ALPHA_TO_ONE_ARB", GLboolean,656 ["ctx->Multisample.SampleAlphaToOne"], "", ["ARB_multisample"] ),657 ( "GL_SAMPLE_COVERAGE_ARB", GLboolean,658 ["ctx->Multisample.SampleCoverage"], "", ["ARB_multisample"] ),659 ( "GL_SAMPLE_COVERAGE_VALUE_ARB", GLfloat,660 ["ctx->Multisample.SampleCoverageValue"], "", ["ARB_multisample"] ),661 ( "GL_SAMPLE_COVERAGE_INVERT_ARB", GLboolean,662 ["ctx->Multisample.SampleCoverageInvert"], "", ["ARB_multisample"] ),663 ( "GL_SAMPLE_BUFFERS_ARB", GLint,664 ["ctx->DrawBuffer->Visual.sampleBuffers"], "", ["ARB_multisample"] ),665 ( "GL_SAMPLES_ARB", GLint,666 ["ctx->DrawBuffer->Visual.samples"], "", ["ARB_multisample"] ),667 # GL_IBM_rasterpos_clip668 ( "GL_RASTER_POSITION_UNCLIPPED_IBM", GLboolean,669 ["ctx->Transform.RasterPositionUnclipped"], "", ["IBM_rasterpos_clip"] ),670 # GL_NV_point_sprite671 ( "GL_POINT_SPRITE_NV", GLboolean, ["ctx->Point.PointSprite"], # == GL_POINT_SPRITE_ARB672 "", ["NV_point_sprite", "ARB_point_sprite"] ),673 ( "GL_POINT_SPRITE_R_MODE_NV", GLenum, ["ctx->Point.SpriteRMode"],674 "", ["NV_point_sprite"] ),675 ( "GL_POINT_SPRITE_COORD_ORIGIN", GLenum, ["ctx->Point.SpriteOrigin"],676 "", ["NV_point_sprite", "ARB_point_sprite"] ),677 # GL_SGIS_generate_mipmap678 ( "GL_GENERATE_MIPMAP_HINT_SGIS", GLenum, ["ctx->Hint.GenerateMipmap"],679 "", ["SGIS_generate_mipmap"] ),680 # GL_NV_vertex_program681 ( "GL_VERTEX_PROGRAM_BINDING_NV", GLint,682 ["(ctx->VertexProgram.Current ? ctx->VertexProgram.Current->Base.Id : 0)"],683 "", ["NV_vertex_program"] ),684 ( "GL_VERTEX_ATTRIB_ARRAY0_NV", GLboolean,685 ["ctx->Array.ArrayObj->VertexAttrib[0].Enabled"], "", ["NV_vertex_program"] ),686 ( "GL_VERTEX_ATTRIB_ARRAY1_NV", GLboolean,687 ["ctx->Array.ArrayObj->VertexAttrib[1].Enabled"], "", ["NV_vertex_program"] ),688 ( "GL_VERTEX_ATTRIB_ARRAY2_NV", GLboolean,689 ["ctx->Array.ArrayObj->VertexAttrib[2].Enabled"], "", ["NV_vertex_program"] ),690 ( "GL_VERTEX_ATTRIB_ARRAY3_NV", GLboolean,691 ["ctx->Array.ArrayObj->VertexAttrib[3].Enabled"], "", ["NV_vertex_program"] ),692 ( "GL_VERTEX_ATTRIB_ARRAY4_NV", GLboolean,693 ["ctx->Array.ArrayObj->VertexAttrib[4].Enabled"], "", ["NV_vertex_program"] ),694 ( "GL_VERTEX_ATTRIB_ARRAY5_NV", GLboolean,695 ["ctx->Array.ArrayObj->VertexAttrib[5].Enabled"], "", ["NV_vertex_program"] ),696 ( "GL_VERTEX_ATTRIB_ARRAY6_NV", GLboolean,697 ["ctx->Array.ArrayObj->VertexAttrib[6].Enabled"], "", ["NV_vertex_program"] ),698 ( "GL_VERTEX_ATTRIB_ARRAY7_NV", GLboolean,699 ["ctx->Array.ArrayObj->VertexAttrib[7].Enabled"], "", ["NV_vertex_program"] ),700 ( "GL_VERTEX_ATTRIB_ARRAY8_NV", GLboolean,701 ["ctx->Array.ArrayObj->VertexAttrib[8].Enabled"], "", ["NV_vertex_program"] ),702 ( "GL_VERTEX_ATTRIB_ARRAY9_NV", GLboolean,703 ["ctx->Array.ArrayObj->VertexAttrib[9].Enabled"], "", ["NV_vertex_program"] ),704 ( "GL_VERTEX_ATTRIB_ARRAY10_NV", GLboolean,705 ["ctx->Array.ArrayObj->VertexAttrib[10].Enabled"], "", ["NV_vertex_program"] ),706 ( "GL_VERTEX_ATTRIB_ARRAY11_NV", GLboolean,707 ["ctx->Array.ArrayObj->VertexAttrib[11].Enabled"], "", ["NV_vertex_program"] ),708 ( "GL_VERTEX_ATTRIB_ARRAY12_NV", GLboolean,709 ["ctx->Array.ArrayObj->VertexAttrib[12].Enabled"], "", ["NV_vertex_program"] ),710 ( "GL_VERTEX_ATTRIB_ARRAY13_NV", GLboolean,711 ["ctx->Array.ArrayObj->VertexAttrib[13].Enabled"], "", ["NV_vertex_program"] ),712 ( "GL_VERTEX_ATTRIB_ARRAY14_NV", GLboolean,713 ["ctx->Array.ArrayObj->VertexAttrib[14].Enabled"], "", ["NV_vertex_program"] ),714 ( "GL_VERTEX_ATTRIB_ARRAY15_NV", GLboolean,715 ["ctx->Array.ArrayObj->VertexAttrib[15].Enabled"], "", ["NV_vertex_program"] ),716 ( "GL_MAP1_VERTEX_ATTRIB0_4_NV", GLboolean,717 ["ctx->Eval.Map1Attrib[0]"], "", ["NV_vertex_program"] ),718 ( "GL_MAP1_VERTEX_ATTRIB1_4_NV", GLboolean,719 ["ctx->Eval.Map1Attrib[1]"], "", ["NV_vertex_program"] ),720 ( "GL_MAP1_VERTEX_ATTRIB2_4_NV", GLboolean,721 ["ctx->Eval.Map1Attrib[2]"], "", ["NV_vertex_program"] ),722 ( "GL_MAP1_VERTEX_ATTRIB3_4_NV", GLboolean,723 ["ctx->Eval.Map1Attrib[3]"], "", ["NV_vertex_program"] ),724 ( "GL_MAP1_VERTEX_ATTRIB4_4_NV", GLboolean,725 ["ctx->Eval.Map1Attrib[4]"], "", ["NV_vertex_program"] ),726 ( "GL_MAP1_VERTEX_ATTRIB5_4_NV", GLboolean,727 ["ctx->Eval.Map1Attrib[5]"], "", ["NV_vertex_program"] ),728 ( "GL_MAP1_VERTEX_ATTRIB6_4_NV", GLboolean,729 ["ctx->Eval.Map1Attrib[6]"], "", ["NV_vertex_program"] ),730 ( "GL_MAP1_VERTEX_ATTRIB7_4_NV", GLboolean,731 ["ctx->Eval.Map1Attrib[7]"], "", ["NV_vertex_program"] ),732 ( "GL_MAP1_VERTEX_ATTRIB8_4_NV", GLboolean,733 ["ctx->Eval.Map1Attrib[8]"], "", ["NV_vertex_program"] ),734 ( "GL_MAP1_VERTEX_ATTRIB9_4_NV", GLboolean,735 ["ctx->Eval.Map1Attrib[9]"], "", ["NV_vertex_program"] ),736 ( "GL_MAP1_VERTEX_ATTRIB10_4_NV", GLboolean,737 ["ctx->Eval.Map1Attrib[10]"], "", ["NV_vertex_program"] ),738 ( "GL_MAP1_VERTEX_ATTRIB11_4_NV", GLboolean,739 ["ctx->Eval.Map1Attrib[11]"], "", ["NV_vertex_program"] ),740 ( "GL_MAP1_VERTEX_ATTRIB12_4_NV", GLboolean,741 ["ctx->Eval.Map1Attrib[12]"], "", ["NV_vertex_program"] ),742 ( "GL_MAP1_VERTEX_ATTRIB13_4_NV", GLboolean,743 ["ctx->Eval.Map1Attrib[13]"], "", ["NV_vertex_program"] ),744 ( "GL_MAP1_VERTEX_ATTRIB14_4_NV", GLboolean,745 ["ctx->Eval.Map1Attrib[14]"], "", ["NV_vertex_program"] ),746 ( "GL_MAP1_VERTEX_ATTRIB15_4_NV", GLboolean,747 ["ctx->Eval.Map1Attrib[15]"], "", ["NV_vertex_program"] ),748 # GL_NV_fragment_program749 ( "GL_FRAGMENT_PROGRAM_NV", GLboolean,750 ["ctx->FragmentProgram.Enabled"], "", ["NV_fragment_program"] ),751 ( "GL_FRAGMENT_PROGRAM_BINDING_NV", GLint,752 ["ctx->FragmentProgram.Current ? ctx->FragmentProgram.Current->Base.Id : 0"],753 "", ["NV_fragment_program"] ),754 ( "GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV", GLint,755 ["MAX_NV_FRAGMENT_PROGRAM_PARAMS"], "", ["NV_fragment_program"] ),756 # GL_NV_texture_rectangle757 ( "GL_TEXTURE_RECTANGLE_NV", GLboolean,758 ["_mesa_IsEnabled(GL_TEXTURE_RECTANGLE_NV)"], "", ["NV_texture_rectangle"] ),759 ( "GL_TEXTURE_BINDING_RECTANGLE_NV", GLint,760 ["ctx->Texture.Unit[ctx->Texture.CurrentUnit].CurrentRect->Name"],761 "", ["NV_texture_rectangle"] ),762 ( "GL_MAX_RECTANGLE_TEXTURE_SIZE_NV", GLint,763 ["ctx->Const.MaxTextureRectSize"], "", ["NV_texture_rectangle"] ),764 # GL_EXT_stencil_two_side765 ( "GL_STENCIL_TEST_TWO_SIDE_EXT", GLboolean,766 ["ctx->Stencil.TestTwoSide"], "", ["EXT_stencil_two_side"] ),767 ( "GL_ACTIVE_STENCIL_FACE_EXT", GLenum,768 ["ctx->Stencil.ActiveFace ? GL_BACK : GL_FRONT"],769 "", ["EXT_stencil_two_side"] ),770 # GL_NV_light_max_exponent771 ( "GL_MAX_SHININESS_NV", GLfloat,772 ["ctx->Const.MaxShininess"], "", ["NV_light_max_exponent"] ),773 ( "GL_MAX_SPOT_EXPONENT_NV", GLfloat,774 ["ctx->Const.MaxSpotExponent"], "", ["NV_light_max_exponent"] ),775 # GL_ARB_vertex_buffer_object776 ( "GL_ARRAY_BUFFER_BINDING_ARB", GLint,777 ["ctx->Array.ArrayBufferObj->Name"], "", ["ARB_vertex_buffer_object"] ),778 ( "GL_VERTEX_ARRAY_BUFFER_BINDING_ARB", GLint,779 ["ctx->Array.ArrayObj->Vertex.BufferObj->Name"], "", ["ARB_vertex_buffer_object"] ),780 ( "GL_NORMAL_ARRAY_BUFFER_BINDING_ARB", GLint,781 ["ctx->Array.ArrayObj->Normal.BufferObj->Name"], "", ["ARB_vertex_buffer_object"] ),782 ( "GL_COLOR_ARRAY_BUFFER_BINDING_ARB", GLint,783 ["ctx->Array.ArrayObj->Color.BufferObj->Name"], "", ["ARB_vertex_buffer_object"] ),784 ( "GL_INDEX_ARRAY_BUFFER_BINDING_ARB", GLint,785 ["ctx->Array.ArrayObj->Index.BufferObj->Name"], "", ["ARB_vertex_buffer_object"] ),786 ( "GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB", GLint,787 ["ctx->Array.ArrayObj->TexCoord[ctx->Array.ActiveTexture].BufferObj->Name"],788 "", ["ARB_vertex_buffer_object"] ),789 ( "GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB", GLint,790 ["ctx->Array.ArrayObj->EdgeFlag.BufferObj->Name"], "", ["ARB_vertex_buffer_object"] ),791 ( "GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB", GLint,792 ["ctx->Array.ArrayObj->SecondaryColor.BufferObj->Name"],793 "", ["ARB_vertex_buffer_object"] ),794 ( "GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB", GLint,795 ["ctx->Array.ArrayObj->FogCoord.BufferObj->Name"],796 "", ["ARB_vertex_buffer_object"] ),797 # GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB - not supported798 ( "GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB", GLint,799 ["ctx->Array.ElementArrayBufferObj->Name"],800 "", ["ARB_vertex_buffer_object"] ),801 # GL_EXT_pixel_buffer_object802 ( "GL_PIXEL_PACK_BUFFER_BINDING_EXT", GLint,803 ["ctx->Pack.BufferObj->Name"], "", ["EXT_pixel_buffer_object"] ),804 ( "GL_PIXEL_UNPACK_BUFFER_BINDING_EXT", GLint,805 ["ctx->Unpack.BufferObj->Name"], "", ["EXT_pixel_buffer_object"] ),806 # GL_ARB_vertex_program807 ( "GL_VERTEX_PROGRAM_ARB", GLboolean, # == GL_VERTEX_PROGRAM_NV808 ["ctx->VertexProgram.Enabled"], "",809 ["ARB_vertex_program", "NV_vertex_program"] ),810 ( "GL_VERTEX_PROGRAM_POINT_SIZE_ARB", GLboolean, # == GL_VERTEX_PROGRAM_POINT_SIZE_NV811 ["ctx->VertexProgram.PointSizeEnabled"], "",812 ["ARB_vertex_program", "NV_vertex_program"] ),813 ( "GL_VERTEX_PROGRAM_TWO_SIDE_ARB", GLboolean, # == GL_VERTEX_PROGRAM_TWO_SIDE_NV814 ["ctx->VertexProgram.TwoSideEnabled"], "",815 ["ARB_vertex_program", "NV_vertex_program"] ),816 ( "GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB", GLint, # == GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV817 ["ctx->Const.MaxProgramMatrixStackDepth"], "",818 ["ARB_vertex_program", "ARB_fragment_program", "NV_vertex_program"] ),819 ( "GL_MAX_PROGRAM_MATRICES_ARB", GLint, # == GL_MAX_TRACK_MATRICES_NV820 ["ctx->Const.MaxProgramMatrices"], "",821 ["ARB_vertex_program", "ARB_fragment_program", "NV_vertex_program"] ),822 ( "GL_CURRENT_MATRIX_STACK_DEPTH_ARB", GLboolean, # == GL_CURRENT_MATRIX_STACK_DEPTH_NV823 ["ctx->CurrentStack->Depth + 1"], "",824 ["ARB_vertex_program", "ARB_fragment_program", "NV_vertex_program"] ),825 ( "GL_CURRENT_MATRIX_ARB", GLfloat, # == GL_CURRENT_MATRIX_NV826 ["matrix[0]", "matrix[1]", "matrix[2]", "matrix[3]",827 "matrix[4]", "matrix[5]", "matrix[6]", "matrix[7]",828 "matrix[8]", "matrix[9]", "matrix[10]", "matrix[11]",829 "matrix[12]", "matrix[13]", "matrix[14]", "matrix[15]" ],830 "const GLfloat *matrix = ctx->CurrentStack->Top->m;",831 ["ARB_vertex_program", "ARB_fragment_program", "NV_fragment_program"] ),832 ( "GL_TRANSPOSE_CURRENT_MATRIX_ARB", GLfloat,833 ["matrix[0]", "matrix[4]", "matrix[8]", "matrix[12]",834 "matrix[1]", "matrix[5]", "matrix[9]", "matrix[13]",835 "matrix[2]", "matrix[6]", "matrix[10]", "matrix[14]",836 "matrix[3]", "matrix[7]", "matrix[11]", "matrix[15]"],837 "const GLfloat *matrix = ctx->CurrentStack->Top->m;",838 ["ARB_vertex_program", "ARB_fragment_program"] ),839 ( "GL_MAX_VERTEX_ATTRIBS_ARB", GLint,840 ["ctx->Const.VertexProgram.MaxAttribs"], "", ["ARB_vertex_program"] ),841 ( "GL_PROGRAM_ERROR_POSITION_ARB", GLint, # == GL_PROGRAM_ERROR_POSITION_NV842 ["ctx->Program.ErrorPos"], "", ["NV_vertex_program",843 "ARB_vertex_program", "NV_fragment_program", "ARB_fragment_program"] ),844 # GL_ARB_fragment_program845 ( "GL_FRAGMENT_PROGRAM_ARB", GLboolean,846 ["ctx->FragmentProgram.Enabled"], "", ["ARB_fragment_program"] ),847 ( "GL_MAX_TEXTURE_COORDS_ARB", GLint, # == GL_MAX_TEXTURE_COORDS_NV848 ["ctx->Const.MaxTextureCoordUnits"], "",849 ["ARB_fragment_program", "NV_fragment_program"] ),850 ( "GL_MAX_TEXTURE_IMAGE_UNITS_ARB", GLint, # == GL_MAX_TEXTURE_IMAGE_UNITS_NV851 ["ctx->Const.MaxTextureImageUnits"], "",852 ["ARB_fragment_program", "NV_fragment_program"] ),853 # GL_EXT_depth_bounds_test854 ( "GL_DEPTH_BOUNDS_TEST_EXT", GLboolean,855 ["ctx->Depth.BoundsTest"], "", ["EXT_depth_bounds_test"] ),856 ( "GL_DEPTH_BOUNDS_EXT", GLfloat,857 ["ctx->Depth.BoundsMin", "ctx->Depth.BoundsMax"],858 "", ["EXT_depth_bounds_test"] ),859 # GL_MESA_program_debug860 ( "GL_FRAGMENT_PROGRAM_CALLBACK_MESA", GLboolean,861 ["ctx->FragmentProgram.CallbackEnabled"], "", ["MESA_program_debug"] ),862 ( "GL_VERTEX_PROGRAM_CALLBACK_MESA", GLboolean,863 ["ctx->VertexProgram.CallbackEnabled"], "", ["MESA_program_debug"] ),864 ( "GL_FRAGMENT_PROGRAM_POSITION_MESA", GLint,865 ["ctx->FragmentProgram.CurrentPosition"], "", ["MESA_program_debug"] ),866 ( "GL_VERTEX_PROGRAM_POSITION_MESA", GLint,867 ["ctx->VertexProgram.CurrentPosition"], "", ["MESA_program_debug"] ),868 # GL_ARB_draw_buffers869 ( "GL_MAX_DRAW_BUFFERS_ARB", GLint,870 ["ctx->Const.MaxDrawBuffers"], "", ["ARB_draw_buffers"] ),871 ( "GL_DRAW_BUFFER0_ARB", GLenum,872 ["ctx->DrawBuffer->ColorDrawBuffer[0]"], "", ["ARB_draw_buffers"] ),873 ( "GL_DRAW_BUFFER1_ARB", GLenum,874 ["buffer"],875 """GLenum buffer;876 if (pname - GL_DRAW_BUFFER0_ARB >= ctx->Const.MaxDrawBuffers) {877 _mesa_error(ctx, GL_INVALID_ENUM, "glGet(GL_DRAW_BUFFERx_ARB)");878 return;879 }880 buffer = ctx->DrawBuffer->ColorDrawBuffer[1];""", ["ARB_draw_buffers"] ),881 ( "GL_DRAW_BUFFER2_ARB", GLenum,882 ["buffer"],883 """GLenum buffer;884 if (pname - GL_DRAW_BUFFER0_ARB >= ctx->Const.MaxDrawBuffers) {885 _mesa_error(ctx, GL_INVALID_ENUM, "glGet(GL_DRAW_BUFFERx_ARB)");886 return;887 }888 buffer = ctx->DrawBuffer->ColorDrawBuffer[2];""", ["ARB_draw_buffers"] ),889 ( "GL_DRAW_BUFFER3_ARB", GLenum,890 ["buffer"],891 """GLenum buffer;892 if (pname - GL_DRAW_BUFFER0_ARB >= ctx->Const.MaxDrawBuffers) {893 _mesa_error(ctx, GL_INVALID_ENUM, "glGet(GL_DRAW_BUFFERx_ARB)");894 return;895 }896 buffer = ctx->DrawBuffer->ColorDrawBuffer[3];""", ["ARB_draw_buffers"] ),897 # XXX Add more GL_DRAW_BUFFERn_ARB entries as needed in the future898 # GL_OES_read_format899 ( "GL_IMPLEMENTATION_COLOR_READ_TYPE_OES", GLint,900 ["ctx->Const.ColorReadType"], "", ["OES_read_format"] ),901 ( "GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES", GLint,902 ["ctx->Const.ColorReadFormat"], "", ["OES_read_format"] ),903 # GL_ATI_fragment_shader904 ( "GL_NUM_FRAGMENT_REGISTERS_ATI", GLint, ["6"], "", ["ATI_fragment_shader"] ),905 ( "GL_NUM_FRAGMENT_CONSTANTS_ATI", GLint, ["8"], "", ["ATI_fragment_shader"] ),906 ( "GL_NUM_PASSES_ATI", GLint, ["2"], "", ["ATI_fragment_shader"] ),907 ( "GL_NUM_INSTRUCTIONS_PER_PASS_ATI", GLint, ["8"], "", ["ATI_fragment_shader"] ),908 ( "GL_NUM_INSTRUCTIONS_TOTAL_ATI", GLint, ["16"], "", ["ATI_fragment_shader"] ),909 ( "GL_COLOR_ALPHA_PAIRING_ATI", GLboolean, ["GL_TRUE"], "", ["ATI_fragment_shader"] ),910 ( "GL_NUM_LOOPBACK_COMPONENTS_ATI", GLint, ["3"], "", ["ATI_fragment_shader"] ),911 ( "GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI", GLint, ["3"], "", ["ATI_fragment_shader"] ),912 # OpenGL 2.0913 ( "GL_STENCIL_BACK_FUNC", GLenum, ["ctx->Stencil.Function[1]"], "", None ),914 ( "GL_STENCIL_BACK_VALUE_MASK", GLint, ["ctx->Stencil.ValueMask[1]"], "", None ),915 ( "GL_STENCIL_BACK_WRITEMASK", GLint, ["ctx->Stencil.WriteMask[1]"], "", None ),916 ( "GL_STENCIL_BACK_REF", GLint, ["ctx->Stencil.Ref[1]"], "", None ),917 ( "GL_STENCIL_BACK_FAIL", GLenum, ["ctx->Stencil.FailFunc[1]"], "", None ),918 ( "GL_STENCIL_BACK_PASS_DEPTH_FAIL", GLenum, ["ctx->Stencil.ZFailFunc[1]"], "", None ),919 ( "GL_STENCIL_BACK_PASS_DEPTH_PASS", GLenum, ["ctx->Stencil.ZPassFunc[1]"], "", None ),920 # GL_EXT_framebuffer_object921 ( "GL_FRAMEBUFFER_BINDING_EXT", GLint, ["ctx->DrawBuffer->Name"], "",922 ["EXT_framebuffer_object"] ),923 ( "GL_RENDERBUFFER_BINDING_EXT", GLint,924 ["ctx->CurrentRenderbuffer ? ctx->CurrentRenderbuffer->Name : 0"], "",925 ["EXT_framebuffer_object"] ),926 ( "GL_MAX_COLOR_ATTACHMENTS_EXT", GLint,927 ["ctx->Const.MaxColorAttachments"], "",928 ["EXT_framebuffer_object"] ),929 ( "GL_MAX_RENDERBUFFER_SIZE_EXT", GLint,930 ["ctx->Const.MaxRenderbufferSize"], "",931 ["EXT_framebuffer_object"] ),932 # GL_ARB_fragment_shader933 ( "GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB", GLint,934 ["ctx->Const.FragmentProgram.MaxUniformComponents"], "",935 ["ARB_fragment_shader"] ),936 ( "GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB", GLenum,937 ["ctx->Hint.FragmentShaderDerivative"], "", ["ARB_fragment_shader"] ),938 # GL_ARB_vertex_shader939 ( "GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB", GLint,940 ["ctx->Const.VertexProgram.MaxUniformComponents"], "",941 ["ARB_vertex_shader"] ),942 ( "GL_MAX_VARYING_FLOATS_ARB", GLint,943 ["ctx->Const.MaxVarying * 4"], "", ["ARB_vertex_shader"] ),944 ( "GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB", GLint,945 ["ctx->Const.MaxVertexTextureImageUnits"], "", ["ARB_vertex_shader"] ),946 ( "GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB", GLint,947 ["MAX_COMBINED_TEXTURE_IMAGE_UNITS"], "", ["ARB_vertex_shader"] ),948 # GL_ARB_shader_objects949 # Actually, this token isn't part of GL_ARB_shader_objects, but is950 # close enough for now.951 ( "GL_CURRENT_PROGRAM", GLint,952 ["ctx->Shader.CurrentProgram ? ctx->Shader.CurrentProgram->Name : 0"],953 "", ["ARB_shader_objects"] )954]955def ConversionFunc(fromType, toType):956 """Return the name of the macro to convert between two data types."""957 if fromType == toType:958 return ""959 elif fromType == GLfloat and toType == GLint:960 return "IROUND"961 elif fromType == GLfloatN and toType == GLfloat:962 return ""963 elif fromType == GLint and toType == GLfloat: # but not GLfloatN!964 return "(GLfloat)"965 else:966 if fromType == GLfloatN:967 fromType = GLfloat968 fromStr = TypeStrings[fromType]969 fromStr = string.upper(fromStr[2:])970 toStr = TypeStrings[toType]971 toStr = string.upper(toStr[2:])972 return fromStr + "_TO_" + toStr973def EmitGetFunction(stateVars, returnType):974 """Emit the code to implement glGetBooleanv, glGetIntegerv or glGetFloatv."""975 assert (returnType == GLboolean or976 returnType == GLint or977 returnType == GLfloat)978 strType = TypeStrings[returnType]979 # Capitalize first letter of return type980 if returnType == GLint:981 function = "GetIntegerv"982 elif returnType == GLboolean:983 function = "GetBooleanv"984 elif returnType == GLfloat:985 function = "GetFloatv"986 else:987 abort()988 print "void GLAPIENTRY"989 print "_mesa_%s( GLenum pname, %s *params )" % (function, strType)990 print "{"991 print " GET_CURRENT_CONTEXT(ctx);"992 print " ASSERT_OUTSIDE_BEGIN_END(ctx);"993 print ""994 print " if (!params)"995 print " return;"996 print ""997 print " if (ctx->NewState)"998 print " _mesa_update_state(ctx);"999 print ""1000 print " if (ctx->Driver.%s &&" % function1001 print " ctx->Driver.%s(ctx, pname, params))" % function1002 print " return;"1003 print ""1004 print " switch (pname) {"1005 for (name, varType, state, optionalCode, extensions) in stateVars:1006 print " case " + name + ":"1007 if extensions:1008 if len(extensions) == 1:1009 print (' CHECK_EXT1(%s, "%s");' %1010 (extensions[0], function))1011 elif len(extensions) == 2:1012 print (' CHECK_EXT2(%s, %s, "%s");' %1013 (extensions[0], extensions[1], function))1014 elif len(extensions) == 3:1015 print (' CHECK_EXT3(%s, %s, %s, "%s");' %1016 (extensions[0], extensions[1], extensions[2], function))1017 else:1018 assert len(extensions) == 41019 print (' CHECK_EXT4(%s, %s, %s, %s, "%s");' %1020 (extensions[0], extensions[1], extensions[2], extensions[3], function))1021 if optionalCode:1022 print " {"1023 print " " + optionalCode1024 conversion = ConversionFunc(varType, returnType)1025 n = len(state)1026 for i in range(n):1027 if conversion:1028 print " params[%d] = %s(%s);" % (i, conversion, state[i])1029 else:1030 print " params[%d] = %s;" % (i, state[i])1031 if optionalCode:1032 print " }"1033 print " break;"1034 print " default:"1035 print ' _mesa_error(ctx, GL_INVALID_ENUM, "gl%s(pname=0x%%x)", pname);' % function1036 print " }"1037 print "}"1038 print ""1039 return1040def EmitHeader():1041 """Print the get.c file header."""1042 print """1043/***1044 *** NOTE!!! DO NOT EDIT THIS FILE!!! IT IS GENERATED BY get_gen.py1045 ***/1046#include "glheader.h"1047#include "context.h"1048#include "enable.h"1049#include "extensions.h"1050#include "fbobject.h"1051#include "get.h"1052#include "macros.h"1053#include "mtypes.h"1054#include "state.h"1055#include "texcompress.h"1056#define FLOAT_TO_BOOLEAN(X) ( (X) ? GL_TRUE : GL_FALSE )1057#define INT_TO_BOOLEAN(I) ( (I) ? GL_TRUE : GL_FALSE )1058#define ENUM_TO_BOOLEAN(E) ( (E) ? GL_TRUE : GL_FALSE )1059#define ENUM_TO_INT(E) ( (GLint) (E) )1060#define ENUM_TO_FLOAT(E) ( (GLfloat) (E) )1061#define BOOLEAN_TO_INT(B) ( (GLint) (B) )1062#define BOOLEAN_TO_FLOAT(B) ( (B) ? 1.0F : 0.0F )1063/*1064 * Check if named extension is enabled, if not generate error and return.1065 */1066#define CHECK_EXT1(EXT1, FUNC) \\1067 if (!ctx->Extensions.EXT1) { \\1068 _mesa_error(ctx, GL_INVALID_ENUM, FUNC "(0x%x)", (int) pname); \\1069 return; \\1070 }1071/*1072 * Check if either of two extensions is enabled.1073 */1074#define CHECK_EXT2(EXT1, EXT2, FUNC) \\1075 if (!ctx->Extensions.EXT1 && !ctx->Extensions.EXT2) { \\1076 _mesa_error(ctx, GL_INVALID_ENUM, FUNC "(0x%x)", (int) pname); \\1077 return; \\1078 }1079/*1080 * Check if either of three extensions is enabled.1081 */1082#define CHECK_EXT3(EXT1, EXT2, EXT3, FUNC) \\1083 if (!ctx->Extensions.EXT1 && !ctx->Extensions.EXT2 && \\1084 !ctx->Extensions.EXT3) { \\1085 _mesa_error(ctx, GL_INVALID_ENUM, FUNC "(0x%x)", (int) pname); \\1086 return; \\1087 }1088/*1089 * Check if either of four extensions is enabled.1090 */1091#define CHECK_EXT4(EXT1, EXT2, EXT3, EXT4, FUNC) \\1092 if (!ctx->Extensions.EXT1 && !ctx->Extensions.EXT2 && \\1093 !ctx->Extensions.EXT3 && !ctx->Extensions.EXT4) { \\1094 _mesa_error(ctx, GL_INVALID_ENUM, FUNC "(0x%x)", (int) pname); \\1095 return; \\1096 }1097"""1098 return1099def EmitGetDoublev():1100 print """1101void GLAPIENTRY1102_mesa_GetDoublev( GLenum pname, GLdouble *params )1103{1104 const GLfloat magic = -1234.5F;1105 GLfloat values[16];1106 GLuint i;1107 if (!params)1108 return;1109 /* Init temp array to magic numbers so we can figure out how many values1110 * are returned by the GetFloatv() call.1111 */1112 for (i = 0; i < 16; i++)1113 values[i] = magic;1114 _mesa_GetFloatv(pname, values);1115 1116 for (i = 0; i < 16 && values[i] != magic; i++)1117 params[i] = (GLdouble) values[i];1118}1119"""1120 1121EmitHeader()1122# XXX Maybe sort the StateVars list1123EmitGetFunction(StateVars, GLboolean)1124EmitGetFunction(StateVars, GLfloat)1125EmitGetFunction(StateVars, GLint)...
http.py
Source:http.py
1from __future__ import unicode_literals2import errno3import os4import socket5import time6import random7import re8from .common import FileDownloader9from ..compat import (10 compat_str,11 compat_urllib_error,12)13from ..utils import (14 ContentTooShortError,15 encodeFilename,16 int_or_none,17 sanitize_open,18 sanitized_Request,19 write_xattr,20 XAttrMetadataError,21 XAttrUnavailableError,22)23class HttpFD(FileDownloader):24 def real_download(self, filename, info_dict):25 url = info_dict['url']26 class DownloadContext(dict):27 __getattr__ = dict.get28 __setattr__ = dict.__setitem__29 __delattr__ = dict.__delitem__30 ctx = DownloadContext()31 ctx.filename = filename32 ctx.tmpfilename = self.temp_name(filename)33 ctx.stream = None34 # Do not include the Accept-Encoding header35 headers = {'Youtubedl-no-compression': 'True'}36 add_headers = info_dict.get('http_headers')37 if add_headers:38 headers.update(add_headers)39 is_test = self.params.get('test', False)40 chunk_size = self._TEST_FILE_SIZE if is_test else (41 info_dict.get('downloader_options', {}).get('http_chunk_size')42 or self.params.get('http_chunk_size') or 0)43 ctx.open_mode = 'wb'44 ctx.resume_len = 045 ctx.data_len = None46 ctx.block_size = self.params.get('buffersize', 1024)47 ctx.start_time = time.time()48 ctx.chunk_size = None49 if self.params.get('continuedl', True):50 # Establish possible resume length51 if os.path.isfile(encodeFilename(ctx.tmpfilename)):52 ctx.resume_len = os.path.getsize(53 encodeFilename(ctx.tmpfilename))54 ctx.is_resume = ctx.resume_len > 055 count = 056 retries = self.params.get('retries', 0)57 class SucceedDownload(Exception):58 pass59 class RetryDownload(Exception):60 def __init__(self, source_error):61 self.source_error = source_error62 class NextFragment(Exception):63 pass64 def set_range(req, start, end):65 range_header = 'bytes=%d-' % start66 if end:67 range_header += compat_str(end)68 req.add_header('Range', range_header)69 def establish_connection():70 ctx.chunk_size = (random.randint(int(chunk_size * 0.95), chunk_size)71 if not is_test and chunk_size else chunk_size)72 if ctx.resume_len > 0:73 range_start = ctx.resume_len74 if ctx.is_resume:75 self.report_resuming_byte(ctx.resume_len)76 ctx.open_mode = 'ab'77 elif ctx.chunk_size > 0:78 range_start = 079 else:80 range_start = None81 ctx.is_resume = False82 range_end = range_start + ctx.chunk_size - 1 if ctx.chunk_size else None83 if range_end and ctx.data_len is not None and range_end >= ctx.data_len:84 range_end = ctx.data_len - 185 has_range = range_start is not None86 ctx.has_range = has_range87 request = sanitized_Request(url, None, headers)88 if has_range:89 set_range(request, range_start, range_end)90 # Establish connection91 try:92 try:93 ctx.data = self.ydl.urlopen(request)94 except (compat_urllib_error.URLError, ) as err:95 if isinstance(err.reason, socket.timeout):96 raise RetryDownload(err)97 raise err98 # When trying to resume, Content-Range HTTP header of response has to be checked99 # to match the value of requested Range HTTP header. This is due to a webservers100 # that don't support resuming and serve a whole file with no Content-Range101 # set in response despite of requested Range (see102 # https://github.com/ytdl-org/youtube-dl/issues/6057#issuecomment-126129799)103 if has_range:104 content_range = ctx.data.headers.get('Content-Range')105 if content_range:106 content_range_m = re.search(r'bytes (\d+)-(\d+)?(?:/(\d+))?', content_range)107 # Content-Range is present and matches requested Range, resume is possible108 if content_range_m:109 if range_start == int(content_range_m.group(1)):110 content_range_end = int_or_none(content_range_m.group(2))111 content_len = int_or_none(content_range_m.group(3))112 accept_content_len = (113 # Non-chunked download114 not ctx.chunk_size115 # Chunked download and requested piece or116 # its part is promised to be served117 or content_range_end == range_end118 or content_len < range_end)119 if accept_content_len:120 ctx.data_len = content_len121 return122 # Content-Range is either not present or invalid. Assuming remote webserver is123 # trying to send the whole file, resume is not possible, so wiping the local file124 # and performing entire redownload125 self.report_unable_to_resume()126 ctx.resume_len = 0127 ctx.open_mode = 'wb'128 ctx.data_len = int_or_none(ctx.data.info().get('Content-length', None))129 return130 except (compat_urllib_error.HTTPError, ) as err:131 if err.code == 416:132 # Unable to resume (requested range not satisfiable)133 try:134 # Open the connection again without the range header135 ctx.data = self.ydl.urlopen(136 sanitized_Request(url, None, headers))137 content_length = ctx.data.info()['Content-Length']138 except (compat_urllib_error.HTTPError, ) as err:139 if err.code < 500 or err.code >= 600:140 raise141 else:142 # Examine the reported length143 if (content_length is not None144 and (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)):145 # The file had already been fully downloaded.146 # Explanation to the above condition: in issue #175 it was revealed that147 # YouTube sometimes adds or removes a few bytes from the end of the file,148 # changing the file size slightly and causing problems for some users. So149 # I decided to implement a suggested change and consider the file150 # completely downloaded if the file size differs less than 100 bytes from151 # the one in the hard drive.152 self.report_file_already_downloaded(ctx.filename)153 self.try_rename(ctx.tmpfilename, ctx.filename)154 self._hook_progress({155 'filename': ctx.filename,156 'status': 'finished',157 'downloaded_bytes': ctx.resume_len,158 'total_bytes': ctx.resume_len,159 })160 raise SucceedDownload()161 else:162 # The length does not match, we start the download over163 self.report_unable_to_resume()164 ctx.resume_len = 0165 ctx.open_mode = 'wb'166 return167 elif err.code < 500 or err.code >= 600:168 # Unexpected HTTP error169 raise170 raise RetryDownload(err)171 except socket.error as err:172 if err.errno != errno.ECONNRESET:173 # Connection reset is no problem, just retry174 raise175 raise RetryDownload(err)176 def download():177 data_len = ctx.data.info().get('Content-length', None)178 # Range HTTP header may be ignored/unsupported by a webserver179 # (e.g. extractor/scivee.py, extractor/bambuser.py).180 # However, for a test we still would like to download just a piece of a file.181 # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control182 # block size when downloading a file.183 if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE):184 data_len = self._TEST_FILE_SIZE185 if data_len is not None:186 data_len = int(data_len) + ctx.resume_len187 min_data_len = self.params.get('min_filesize')188 max_data_len = self.params.get('max_filesize')189 if min_data_len is not None and data_len < min_data_len:190 self.to_screen('\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))191 return False192 if max_data_len is not None and data_len > max_data_len:193 self.to_screen('\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))194 return False195 byte_counter = 0 + ctx.resume_len196 block_size = ctx.block_size197 start = time.time()198 # measure time over whole while-loop, so slow_down() and best_block_size() work together properly199 now = None # needed for slow_down() in the first loop run200 before = start # start measuring201 def retry(e):202 to_stdout = ctx.tmpfilename == '-'203 if ctx.stream is not None:204 if not to_stdout:205 ctx.stream.close()206 ctx.stream = None207 ctx.resume_len = byte_counter if to_stdout else os.path.getsize(encodeFilename(ctx.tmpfilename))208 raise RetryDownload(e)209 while True:210 try:211 # Download and write212 data_block = ctx.data.read(block_size if data_len is None else min(block_size, data_len - byte_counter))213 # socket.timeout is a subclass of socket.error but may not have214 # errno set215 except socket.timeout as e:216 retry(e)217 except socket.error as e:218 # SSLError on python 2 (inherits socket.error) may have219 # no errno set but this error message220 if e.errno in (errno.ECONNRESET, errno.ETIMEDOUT) or getattr(e, 'message', None) == 'The read operation timed out':221 retry(e)222 raise223 byte_counter += len(data_block)224 # exit loop when download is finished225 if len(data_block) == 0:226 break227 # Open destination file just in time228 if ctx.stream is None:229 try:230 ctx.stream, ctx.tmpfilename = sanitize_open(231 ctx.tmpfilename, ctx.open_mode)232 assert ctx.stream is not None233 ctx.filename = self.undo_temp_name(ctx.tmpfilename)234 self.report_destination(ctx.filename)235 except (OSError, IOError) as err:236 self.report_error('unable to open for writing: %s' % str(err))237 return False238 if self.params.get('xattr_set_filesize', False) and data_len is not None:239 try:240 write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode('utf-8'))241 except (XAttrUnavailableError, XAttrMetadataError) as err:242 self.report_error('unable to set filesize xattr: %s' % str(err))243 try:244 ctx.stream.write(data_block)245 except (IOError, OSError) as err:246 self.to_stderr('\n')247 self.report_error('unable to write data: %s' % str(err))248 return False249 # Apply rate limit250 self.slow_down(start, now, byte_counter - ctx.resume_len)251 # end measuring of one loop run252 now = time.time()253 after = now254 # Adjust block size255 if not self.params.get('noresizebuffer', False):256 block_size = self.best_block_size(after - before, len(data_block))257 before = after258 # Progress message259 speed = self.calc_speed(start, now, byte_counter - ctx.resume_len)260 if ctx.data_len is None:261 eta = None262 else:263 eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len)264 self._hook_progress({265 'status': 'downloading',266 'downloaded_bytes': byte_counter,267 'total_bytes': ctx.data_len,268 'tmpfilename': ctx.tmpfilename,269 'filename': ctx.filename,270 'eta': eta,271 'speed': speed,272 'elapsed': now - ctx.start_time,273 })274 if data_len is not None and byte_counter == data_len:275 break276 if not is_test and ctx.chunk_size and ctx.data_len is not None and byte_counter < ctx.data_len:277 ctx.resume_len = byte_counter278 # ctx.block_size = block_size279 raise NextFragment()280 if ctx.stream is None:281 self.to_stderr('\n')282 self.report_error('Did not get any data blocks')283 return False284 if ctx.tmpfilename != '-':285 ctx.stream.close()286 if data_len is not None and byte_counter != data_len:287 err = ContentTooShortError(byte_counter, int(data_len))288 if count <= retries:289 retry(err)290 raise err291 self.try_rename(ctx.tmpfilename, ctx.filename)292 # Update file modification time293 if self.params.get('updatetime', True):294 info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.info().get('last-modified', None))295 self._hook_progress({296 'downloaded_bytes': byte_counter,297 'total_bytes': byte_counter,298 'filename': ctx.filename,299 'status': 'finished',300 'elapsed': time.time() - ctx.start_time,301 })302 return True303 while count <= retries:304 try:305 establish_connection()306 return download()307 except RetryDownload as e:308 count += 1309 if count <= retries:310 self.report_retry(e.source_error, count, retries)311 continue312 except NextFragment:313 continue314 except SucceedDownload:315 return True316 self.report_error('giving up after %s retries' % retries)...
deform_conv.py
Source:deform_conv.py
1# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved2import math3from functools import lru_cache4import torch5from torch import nn6from torch.autograd import Function7from torch.autograd.function import once_differentiable8from torch.nn.modules.utils import _pair9from detectron2 import _C10from .wrappers import _NewEmptyTensorOp11class _DeformConv(Function):12 @staticmethod13 def forward(14 ctx,15 input,16 offset,17 weight,18 stride=1,19 padding=0,20 dilation=1,21 groups=1,22 deformable_groups=1,23 im2col_step=64,24 ):25 if input is not None and input.dim() != 4:26 raise ValueError(27 "Expected 4D tensor as input, got {}D tensor instead.".format(input.dim())28 )29 ctx.stride = _pair(stride)30 ctx.padding = _pair(padding)31 ctx.dilation = _pair(dilation)32 ctx.groups = groups33 ctx.deformable_groups = deformable_groups34 ctx.im2col_step = im2col_step35 ctx.save_for_backward(input, offset, weight)36 output = input.new_empty(37 _DeformConv._output_size(input, weight, ctx.padding, ctx.dilation, ctx.stride)38 )39 ctx.bufs_ = [input.new_empty(0), input.new_empty(0)] # columns, ones40 if not input.is_cuda:41 raise NotImplementedError42 else:43 cur_im2col_step = _DeformConv._cal_im2col_step(input.shape[0], ctx.im2col_step)44 assert (input.shape[0] % cur_im2col_step) == 0, "im2col step must divide batchsize"45 _C.deform_conv_forward(46 input,47 weight,48 offset,49 output,50 ctx.bufs_[0],51 ctx.bufs_[1],52 weight.size(3),53 weight.size(2),54 ctx.stride[1],55 ctx.stride[0],56 ctx.padding[1],57 ctx.padding[0],58 ctx.dilation[1],59 ctx.dilation[0],60 ctx.groups,61 ctx.deformable_groups,62 cur_im2col_step,63 )64 return output65 @staticmethod66 @once_differentiable67 def backward(ctx, grad_output):68 input, offset, weight = ctx.saved_tensors69 grad_input = grad_offset = grad_weight = None70 if not grad_output.is_cuda:71 raise NotImplementedError72 else:73 cur_im2col_step = _DeformConv._cal_im2col_step(input.shape[0], ctx.im2col_step)74 assert (input.shape[0] % cur_im2col_step) == 0, "im2col step must divide batchsize"75 if ctx.needs_input_grad[0] or ctx.needs_input_grad[1]:76 grad_input = torch.zeros_like(input)77 grad_offset = torch.zeros_like(offset)78 _C.deform_conv_backward_input(79 input,80 offset,81 grad_output,82 grad_input,83 grad_offset,84 weight,85 ctx.bufs_[0],86 weight.size(3),87 weight.size(2),88 ctx.stride[1],89 ctx.stride[0],90 ctx.padding[1],91 ctx.padding[0],92 ctx.dilation[1],93 ctx.dilation[0],94 ctx.groups,95 ctx.deformable_groups,96 cur_im2col_step,97 )98 if ctx.needs_input_grad[2]:99 grad_weight = torch.zeros_like(weight)100 _C.deform_conv_backward_filter(101 input,102 offset,103 grad_output,104 grad_weight,105 ctx.bufs_[0],106 ctx.bufs_[1],107 weight.size(3),108 weight.size(2),109 ctx.stride[1],110 ctx.stride[0],111 ctx.padding[1],112 ctx.padding[0],113 ctx.dilation[1],114 ctx.dilation[0],115 ctx.groups,116 ctx.deformable_groups,117 1,118 cur_im2col_step,119 )120 return grad_input, grad_offset, grad_weight, None, None, None, None, None, None121 @staticmethod122 def _output_size(input, weight, padding, dilation, stride):123 channels = weight.size(0)124 output_size = (input.size(0), channels)125 for d in range(input.dim() - 2):126 in_size = input.size(d + 2)127 pad = padding[d]128 kernel = dilation[d] * (weight.size(d + 2) - 1) + 1129 stride_ = stride[d]130 output_size += ((in_size + (2 * pad) - kernel) // stride_ + 1,)131 if not all(map(lambda s: s > 0, output_size)):132 raise ValueError(133 "convolution input is too small (output would be {})".format(134 "x".join(map(str, output_size))135 )136 )137 return output_size138 @staticmethod139 @lru_cache(maxsize=128)140 def _cal_im2col_step(input_size, default_size):141 """142 Calculate proper im2col step size, which should be divisible by input_size and not larger143 than prefer_size. Meanwhile the step size should be as large as possible to be more144 efficient. So we choose the largest one among all divisors of input_size which are smaller145 than prefer_size.146 :param input_size: input batch size .147 :param default_size: default preferred im2col step size.148 :return: the largest proper step size.149 """150 if input_size <= default_size:151 return input_size152 best_step = 1153 for step in range(2, min(int(math.sqrt(input_size)) + 1, default_size)):154 if input_size % step == 0:155 if input_size // step <= default_size:156 return input_size // step157 best_step = step158 return best_step159class _ModulatedDeformConv(Function):160 @staticmethod161 def forward(162 ctx,163 input,164 offset,165 mask,166 weight,167 bias=None,168 stride=1,169 padding=0,170 dilation=1,171 groups=1,172 deformable_groups=1,173 ):174 ctx.stride = stride175 ctx.padding = padding176 ctx.dilation = dilation177 ctx.groups = groups178 ctx.deformable_groups = deformable_groups179 ctx.with_bias = bias is not None180 if not ctx.with_bias:181 bias = input.new_empty(1) # fake tensor182 if not input.is_cuda:183 raise NotImplementedError184 if (185 weight.requires_grad186 or mask.requires_grad187 or offset.requires_grad188 or input.requires_grad189 ):190 ctx.save_for_backward(input, offset, mask, weight, bias)191 output = input.new_empty(_ModulatedDeformConv._infer_shape(ctx, input, weight))192 ctx._bufs = [input.new_empty(0), input.new_empty(0)]193 _C.modulated_deform_conv_forward(194 input,195 weight,196 bias,197 ctx._bufs[0],198 offset,199 mask,200 output,201 ctx._bufs[1],202 weight.shape[2],203 weight.shape[3],204 ctx.stride,205 ctx.stride,206 ctx.padding,207 ctx.padding,208 ctx.dilation,209 ctx.dilation,210 ctx.groups,211 ctx.deformable_groups,212 ctx.with_bias,213 )214 return output215 @staticmethod216 @once_differentiable217 def backward(ctx, grad_output):218 if not grad_output.is_cuda:219 raise NotImplementedError220 input, offset, mask, weight, bias = ctx.saved_tensors221 grad_input = torch.zeros_like(input)222 grad_offset = torch.zeros_like(offset)223 grad_mask = torch.zeros_like(mask)224 grad_weight = torch.zeros_like(weight)225 grad_bias = torch.zeros_like(bias)226 _C.modulated_deform_conv_backward(227 input,228 weight,229 bias,230 ctx._bufs[0],231 offset,232 mask,233 ctx._bufs[1],234 grad_input,235 grad_weight,236 grad_bias,237 grad_offset,238 grad_mask,239 grad_output,240 weight.shape[2],241 weight.shape[3],242 ctx.stride,243 ctx.stride,244 ctx.padding,245 ctx.padding,246 ctx.dilation,247 ctx.dilation,248 ctx.groups,249 ctx.deformable_groups,250 ctx.with_bias,251 )252 if not ctx.with_bias:253 grad_bias = None254 return (255 grad_input,256 grad_offset,257 grad_mask,258 grad_weight,259 grad_bias,260 None,261 None,262 None,263 None,264 None,265 )266 @staticmethod267 def _infer_shape(ctx, input, weight):268 n = input.size(0)269 channels_out = weight.size(0)270 height, width = input.shape[2:4]271 kernel_h, kernel_w = weight.shape[2:4]272 height_out = (273 height + 2 * ctx.padding - (ctx.dilation * (kernel_h - 1) + 1)274 ) // ctx.stride + 1275 width_out = (276 width + 2 * ctx.padding - (ctx.dilation * (kernel_w - 1) + 1)277 ) // ctx.stride + 1278 return n, channels_out, height_out, width_out279deform_conv = _DeformConv.apply280modulated_deform_conv = _ModulatedDeformConv.apply281class DeformConv(nn.Module):282 def __init__(283 self,284 in_channels,285 out_channels,286 kernel_size,287 stride=1,288 padding=0,289 dilation=1,290 groups=1,291 deformable_groups=1,292 bias=False,293 norm=None,294 activation=None,295 ):296 """297 Deformable convolution.298 Arguments are similar to :class:`Conv2D`. Extra arguments:299 Args:300 deformable_groups (int): number of groups used in deformable convolution.301 norm (nn.Module, optional): a normalization layer302 activation (callable(Tensor) -> Tensor): a callable activation function303 """304 super(DeformConv, self).__init__()305 assert not bias306 assert in_channels % groups == 0, "in_channels {} cannot be divisible by groups {}".format(307 in_channels, groups308 )309 assert (310 out_channels % groups == 0311 ), "out_channels {} cannot be divisible by groups {}".format(out_channels, groups)312 self.in_channels = in_channels313 self.out_channels = out_channels314 self.kernel_size = _pair(kernel_size)315 self.stride = _pair(stride)316 self.padding = _pair(padding)317 self.dilation = _pair(dilation)318 self.groups = groups319 self.deformable_groups = deformable_groups320 self.norm = norm321 self.activation = activation322 self.weight = nn.Parameter(323 torch.Tensor(out_channels, in_channels // self.groups, *self.kernel_size)324 )325 self.bias = None326 nn.init.kaiming_uniform_(self.weight, nonlinearity="relu")327 def forward(self, x, offset):328 if x.numel() == 0:329 # When input is empty, we want to return a empty tensor with "correct" shape,330 # So that the following operations will not panic331 # if they check for the shape of the tensor.332 # This computes the height and width of the output tensor333 output_shape = [334 (i + 2 * p - (di * (k - 1) + 1)) // s + 1335 for i, p, di, k, s in zip(336 x.shape[-2:], self.padding, self.dilation, self.kernel_size, self.stride337 )338 ]339 output_shape = [x.shape[0], self.weight.shape[0]] + output_shape340 return _NewEmptyTensorOp.apply(x, output_shape)341 x = deform_conv(342 x,343 offset,344 self.weight,345 self.stride,346 self.padding,347 self.dilation,348 self.groups,349 self.deformable_groups,350 )351 if self.norm is not None:352 x = self.norm(x)353 if self.activation is not None:354 x = self.activation(x)355 return x356 def extra_repr(self):357 tmpstr = "in_channels=" + str(self.in_channels)358 tmpstr += ", out_channels=" + str(self.out_channels)359 tmpstr += ", kernel_size=" + str(self.kernel_size)360 tmpstr += ", stride=" + str(self.stride)361 tmpstr += ", padding=" + str(self.padding)362 tmpstr += ", dilation=" + str(self.dilation)363 tmpstr += ", groups=" + str(self.groups)364 tmpstr += ", deformable_groups=" + str(self.deformable_groups)365 tmpstr += ", bias=False"366 return tmpstr367class ModulatedDeformConv(nn.Module):368 def __init__(369 self,370 in_channels,371 out_channels,372 kernel_size,373 stride=1,374 padding=0,375 dilation=1,376 groups=1,377 deformable_groups=1,378 bias=True,379 norm=None,380 activation=None,381 ):382 """383 Modulated deformable convolution.384 Arguments are similar to :class:`Conv2D`. Extra arguments:385 Args:386 deformable_groups (int): number of groups used in deformable convolution.387 norm (nn.Module, optional): a normalization layer388 activation (callable(Tensor) -> Tensor): a callable activation function389 """390 super(ModulatedDeformConv, self).__init__()391 self.in_channels = in_channels392 self.out_channels = out_channels393 self.kernel_size = _pair(kernel_size)394 self.stride = stride395 self.padding = padding396 self.dilation = dilation397 self.groups = groups398 self.deformable_groups = deformable_groups399 self.with_bias = bias400 self.norm = norm401 self.activation = activation402 self.weight = nn.Parameter(403 torch.Tensor(out_channels, in_channels // groups, *self.kernel_size)404 )405 if bias:406 self.bias = nn.Parameter(torch.Tensor(out_channels))407 else:408 self.bias = None409 nn.init.kaiming_uniform_(self.weight, nonlinearity="relu")410 if self.bias is not None:411 nn.init.constant_(self.bias, 0)412 def forward(self, x, offset, mask):413 if x.numel() == 0:414 output_shape = [415 (i + 2 * p - (di * (k - 1) + 1)) // s + 1416 for i, p, di, k, s in zip(417 x.shape[-2:], self.padding, self.dilation, self.kernel_size, self.stride418 )419 ]420 output_shape = [x.shape[0], self.weight.shape[0]] + output_shape421 return _NewEmptyTensorOp.apply(x, output_shape)422 x = modulated_deform_conv(423 x,424 offset,425 mask,426 self.weight,427 self.bias,428 self.stride,429 self.padding,430 self.dilation,431 self.groups,432 self.deformable_groups,433 )434 if self.norm is not None:435 x = self.norm(x)436 if self.activation is not None:437 x = self.activation(x)438 return x439 def extra_repr(self):440 tmpstr = "in_channels=" + str(self.in_channels)441 tmpstr += ", out_channels=" + str(self.out_channels)442 tmpstr += ", kernel_size=" + str(self.kernel_size)443 tmpstr += ", stride=" + str(self.stride)444 tmpstr += ", padding=" + str(self.padding)445 tmpstr += ", dilation=" + str(self.dilation)446 tmpstr += ", groups=" + str(self.groups)447 tmpstr += ", deformable_groups=" + str(self.deformable_groups)448 tmpstr += ", bias=" + str(self.with_bias)...
fragment.py
Source:fragment.py
1from __future__ import division, unicode_literals2import os3import time4import json5from .common import FileDownloader6from .http import HttpFD7from ..utils import (8 error_to_compat_str,9 encodeFilename,10 sanitize_open,11 sanitized_Request,12)13class HttpQuietDownloader(HttpFD):14 def to_screen(self, *args, **kargs):15 pass16class FragmentFD(FileDownloader):17 """18 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).19 Available options:20 fragment_retries: Number of times to retry a fragment for HTTP error (DASH21 and hlsnative only)22 skip_unavailable_fragments:23 Skip unavailable fragments (DASH and hlsnative only)24 keep_fragments: Keep downloaded fragments on disk after downloading is25 finished26 For each incomplete fragment download youtube-dl keeps on disk a special27 bookkeeping file with download state and metadata (in future such files will28 be used for any incomplete download handled by youtube-dl). This file is29 used to properly handle resuming, check download file consistency and detect30 potential errors. The file has a .ytdl extension and represents a standard31 JSON file of the following format:32 extractor:33 Dictionary of extractor related data. TBD.34 downloader:35 Dictionary of downloader related data. May contain following data:36 current_fragment:37 Dictionary with current (being downloaded) fragment data:38 index: 0-based index of current fragment among all fragments39 fragment_count:40 Total count of fragments41 This feature is experimental and file format may change in future.42 """43 def report_retry_fragment(self, err, frag_index, count, retries):44 self.to_screen(45 '[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s)...'46 % (error_to_compat_str(err), frag_index, count, self.format_retries(retries)))47 def report_skip_fragment(self, frag_index):48 self.to_screen('[download] Skipping fragment %d...' % frag_index)49 def _prepare_url(self, info_dict, url):50 headers = info_dict.get('http_headers')51 return sanitized_Request(url, None, headers) if headers else url52 def _prepare_and_start_frag_download(self, ctx):53 self._prepare_frag_download(ctx)54 self._start_frag_download(ctx)55 @staticmethod56 def __do_ytdl_file(ctx):57 return not ctx['live'] and not ctx['tmpfilename'] == '-'58 def _read_ytdl_file(self, ctx):59 assert 'ytdl_corrupt' not in ctx60 stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'r')61 try:62 ctx['fragment_index'] = json.loads(stream.read())['downloader']['current_fragment']['index']63 except Exception:64 ctx['ytdl_corrupt'] = True65 finally:66 stream.close()67 def _write_ytdl_file(self, ctx):68 frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')69 downloader = {70 'current_fragment': {71 'index': ctx['fragment_index'],72 },73 }74 if ctx.get('fragment_count') is not None:75 downloader['fragment_count'] = ctx['fragment_count']76 frag_index_stream.write(json.dumps({'downloader': downloader}))77 frag_index_stream.close()78 def _download_fragment(self, ctx, frag_url, info_dict, headers=None):79 fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])80 success = ctx['dl'].download(fragment_filename, {81 'url': frag_url,82 'http_headers': headers or info_dict.get('http_headers'),83 })84 if not success:85 return False, None86 down, frag_sanitized = sanitize_open(fragment_filename, 'rb')87 ctx['fragment_filename_sanitized'] = frag_sanitized88 frag_content = down.read()89 down.close()90 return True, frag_content91 def _append_fragment(self, ctx, frag_content):92 try:93 ctx['dest_stream'].write(frag_content)94 ctx['dest_stream'].flush()95 finally:96 if self.__do_ytdl_file(ctx):97 self._write_ytdl_file(ctx)98 if not self.params.get('keep_fragments', False):99 os.remove(encodeFilename(ctx['fragment_filename_sanitized']))100 del ctx['fragment_filename_sanitized']101 def _prepare_frag_download(self, ctx):102 if 'live' not in ctx:103 ctx['live'] = False104 if not ctx['live']:105 total_frags_str = '%d' % ctx['total_frags']106 ad_frags = ctx.get('ad_frags', 0)107 if ad_frags:108 total_frags_str += ' (not including %d ad)' % ad_frags109 else:110 total_frags_str = 'unknown (live)'111 self.to_screen(112 '[%s] Total fragments: %s' % (self.FD_NAME, total_frags_str))113 self.report_destination(ctx['filename'])114 dl = HttpQuietDownloader(115 self.ydl,116 {117 'continuedl': True,118 'quiet': True,119 'noprogress': True,120 'ratelimit': self.params.get('ratelimit'),121 'retries': self.params.get('retries', 0),122 'nopart': self.params.get('nopart', False),123 'test': self.params.get('test', False),124 }125 )126 tmpfilename = self.temp_name(ctx['filename'])127 open_mode = 'wb'128 resume_len = 0129 # Establish possible resume length130 if os.path.isfile(encodeFilename(tmpfilename)):131 open_mode = 'ab'132 resume_len = os.path.getsize(encodeFilename(tmpfilename))133 # Should be initialized before ytdl file check134 ctx.update({135 'tmpfilename': tmpfilename,136 'fragment_index': 0,137 })138 if self.__do_ytdl_file(ctx):139 if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):140 self._read_ytdl_file(ctx)141 is_corrupt = ctx.get('ytdl_corrupt') is True142 is_inconsistent = ctx['fragment_index'] > 0 and resume_len == 0143 if is_corrupt or is_inconsistent:144 message = (145 '.ytdl file is corrupt' if is_corrupt else146 'Inconsistent state of incomplete fragment download')147 self.report_warning(148 '%s. Restarting from the beginning...' % message)149 ctx['fragment_index'] = resume_len = 0150 if 'ytdl_corrupt' in ctx:151 del ctx['ytdl_corrupt']152 self._write_ytdl_file(ctx)153 else:154 self._write_ytdl_file(ctx)155 assert ctx['fragment_index'] == 0156 dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)157 ctx.update({158 'dl': dl,159 'dest_stream': dest_stream,160 'tmpfilename': tmpfilename,161 # Total complete fragments downloaded so far in bytes162 'complete_frags_downloaded_bytes': resume_len,163 })164 def _start_frag_download(self, ctx):165 resume_len = ctx['complete_frags_downloaded_bytes']166 total_frags = ctx['total_frags']167 # This dict stores the download progress, it's updated by the progress168 # hook169 state = {170 'status': 'downloading',171 'downloaded_bytes': resume_len,172 'fragment_index': ctx['fragment_index'],173 'fragment_count': total_frags,174 'filename': ctx['filename'],175 'tmpfilename': ctx['tmpfilename'],176 }177 start = time.time()178 ctx.update({179 'started': start,180 # Amount of fragment's bytes downloaded by the time of the previous181 # frag progress hook invocation182 'prev_frag_downloaded_bytes': 0,183 })184 def frag_progress_hook(s):185 if s['status'] not in ('downloading', 'finished'):186 return187 time_now = time.time()188 state['elapsed'] = time_now - start189 frag_total_bytes = s.get('total_bytes') or 0190 if not ctx['live']:191 estimated_size = (192 (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes)193 / (state['fragment_index'] + 1) * total_frags)194 state['total_bytes_estimate'] = estimated_size195 if s['status'] == 'finished':196 state['fragment_index'] += 1197 ctx['fragment_index'] = state['fragment_index']198 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']199 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']200 ctx['prev_frag_downloaded_bytes'] = 0201 else:202 frag_downloaded_bytes = s['downloaded_bytes']203 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']204 if not ctx['live']:205 state['eta'] = self.calc_eta(206 start, time_now, estimated_size - resume_len,207 state['downloaded_bytes'] - resume_len)208 state['speed'] = s.get('speed') or ctx.get('speed')209 ctx['speed'] = state['speed']210 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes211 self._hook_progress(state)212 ctx['dl'].add_progress_hook(frag_progress_hook)213 return start214 def _finish_frag_download(self, ctx):215 ctx['dest_stream'].close()216 if self.__do_ytdl_file(ctx):217 ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))218 if os.path.isfile(ytdl_filename):219 os.remove(ytdl_filename)220 elapsed = time.time() - ctx['started']221 if ctx['tmpfilename'] == '-':222 downloaded_bytes = ctx['complete_frags_downloaded_bytes']223 else:224 self.try_rename(ctx['tmpfilename'], ctx['filename'])225 downloaded_bytes = os.path.getsize(encodeFilename(ctx['filename']))226 self._hook_progress({227 'downloaded_bytes': downloaded_bytes,228 'total_bytes': downloaded_bytes,229 'filename': ctx['filename'],230 'status': 'finished',231 'elapsed': elapsed,...
deform_conv_func.py
Source:deform_conv_func.py
1import torch2from torch.autograd import Function3from torch.autograd.function import once_differentiable4from torch.nn.modules.utils import _pair5from maskrcnn_benchmark import _C6class DeformConvFunction(Function):7 @staticmethod8 def forward(9 ctx,10 input,11 offset,12 weight,13 stride=1,14 padding=0,15 dilation=1,16 groups=1,17 deformable_groups=1,18 im2col_step=6419 ):20 if input is not None and input.dim() != 4:21 raise ValueError(22 "Expected 4D tensor as input, got {}D tensor instead.".format(23 input.dim()))24 ctx.stride = _pair(stride)25 ctx.padding = _pair(padding)26 ctx.dilation = _pair(dilation)27 ctx.groups = groups28 ctx.deformable_groups = deformable_groups29 ctx.im2col_step = im2col_step30 ctx.save_for_backward(input, offset, weight)31 output = input.new_empty(32 DeformConvFunction._output_size(input, weight, ctx.padding,33 ctx.dilation, ctx.stride))34 ctx.bufs_ = [input.new_empty(0), input.new_empty(0)] # columns, ones35 if not input.is_cuda:36 raise NotImplementedError37 else:38 cur_im2col_step = min(ctx.im2col_step, input.shape[0])39 assert (input.shape[0] %40 cur_im2col_step) == 0, 'im2col step must divide batchsize'41 _C.deform_conv_forward(42 input,43 weight,44 offset,45 output,46 ctx.bufs_[0],47 ctx.bufs_[1],48 weight.size(3),49 weight.size(2),50 ctx.stride[1],51 ctx.stride[0],52 ctx.padding[1],53 ctx.padding[0],54 ctx.dilation[1],55 ctx.dilation[0],56 ctx.groups,57 ctx.deformable_groups,58 cur_im2col_step59 )60 return output61 @staticmethod62 @once_differentiable63 def backward(ctx, grad_output):64 input, offset, weight = ctx.saved_tensors65 grad_input = grad_offset = grad_weight = None66 if not grad_output.is_cuda:67 raise NotImplementedError68 else:69 cur_im2col_step = min(ctx.im2col_step, input.shape[0])70 assert (input.shape[0] %71 cur_im2col_step) == 0, 'im2col step must divide batchsize'72 if ctx.needs_input_grad[0] or ctx.needs_input_grad[1]:73 grad_input = torch.zeros_like(input)74 grad_offset = torch.zeros_like(offset)75 _C.deform_conv_backward_input(76 input,77 offset,78 grad_output,79 grad_input,80 grad_offset,81 weight,82 ctx.bufs_[0],83 weight.size(3),84 weight.size(2),85 ctx.stride[1],86 ctx.stride[0],87 ctx.padding[1],88 ctx.padding[0],89 ctx.dilation[1],90 ctx.dilation[0],91 ctx.groups,92 ctx.deformable_groups,93 cur_im2col_step94 )95 if ctx.needs_input_grad[2]:96 grad_weight = torch.zeros_like(weight)97 _C.deform_conv_backward_parameters(98 input,99 offset,100 grad_output,101 grad_weight,102 ctx.bufs_[0],103 ctx.bufs_[1],104 weight.size(3),105 weight.size(2),106 ctx.stride[1],107 ctx.stride[0],108 ctx.padding[1],109 ctx.padding[0],110 ctx.dilation[1],111 ctx.dilation[0],112 ctx.groups,113 ctx.deformable_groups,114 1,115 cur_im2col_step116 )117 return (grad_input, grad_offset, grad_weight, None, None, None, None, None)118 @staticmethod119 def _output_size(input, weight, padding, dilation, stride):120 channels = weight.size(0)121 output_size = (input.size(0), channels)122 for d in range(input.dim() - 2):123 in_size = input.size(d + 2)124 pad = padding[d]125 kernel = dilation[d] * (weight.size(d + 2) - 1) + 1126 stride_ = stride[d]127 output_size += ((in_size + (2 * pad) - kernel) // stride_ + 1, )128 if not all(map(lambda s: s > 0, output_size)):129 raise ValueError(130 "convolution input is too small (output would be {})".format(131 'x'.join(map(str, output_size))))132 return output_size133class ModulatedDeformConvFunction(Function):134 @staticmethod135 def forward(136 ctx,137 input,138 offset,139 mask,140 weight,141 bias=None,142 stride=1,143 padding=0,144 dilation=1,145 groups=1,146 deformable_groups=1147 ):148 ctx.stride = stride149 ctx.padding = padding150 ctx.dilation = dilation151 ctx.groups = groups152 ctx.deformable_groups = deformable_groups153 ctx.with_bias = bias is not None154 if not ctx.with_bias:155 bias = input.new_empty(1) # fake tensor156 if not input.is_cuda:157 raise NotImplementedError158 if weight.requires_grad or mask.requires_grad or offset.requires_grad \159 or input.requires_grad:160 ctx.save_for_backward(input, offset, mask, weight, bias)161 output = input.new_empty(162 ModulatedDeformConvFunction._infer_shape(ctx, input, weight))163 ctx._bufs = [input.new_empty(0), input.new_empty(0)]164 _C.modulated_deform_conv_forward(165 input,166 weight,167 bias,168 ctx._bufs[0],169 offset,170 mask,171 output,172 ctx._bufs[1],173 weight.shape[2],174 weight.shape[3],175 ctx.stride,176 ctx.stride,177 ctx.padding,178 ctx.padding,179 ctx.dilation,180 ctx.dilation,181 ctx.groups,182 ctx.deformable_groups,183 ctx.with_bias184 )185 return output186 @staticmethod187 @once_differentiable188 def backward(ctx, grad_output):189 if not grad_output.is_cuda:190 raise NotImplementedError191 input, offset, mask, weight, bias = ctx.saved_tensors192 grad_input = torch.zeros_like(input)193 grad_offset = torch.zeros_like(offset)194 grad_mask = torch.zeros_like(mask)195 grad_weight = torch.zeros_like(weight)196 grad_bias = torch.zeros_like(bias)197 _C.modulated_deform_conv_backward(198 input,199 weight,200 bias,201 ctx._bufs[0],202 offset,203 mask,204 ctx._bufs[1],205 grad_input,206 grad_weight,207 grad_bias,208 grad_offset,209 grad_mask,210 grad_output,211 weight.shape[2],212 weight.shape[3],213 ctx.stride,214 ctx.stride,215 ctx.padding,216 ctx.padding,217 ctx.dilation,218 ctx.dilation,219 ctx.groups,220 ctx.deformable_groups,221 ctx.with_bias222 )223 if not ctx.with_bias:224 grad_bias = None225 return (grad_input, grad_offset, grad_mask, grad_weight, grad_bias,226 None, None, None, None, None)227 @staticmethod228 def _infer_shape(ctx, input, weight):229 n = input.size(0)230 channels_out = weight.size(0)231 height, width = input.shape[2:4]232 kernel_h, kernel_w = weight.shape[2:4]233 height_out = (height + 2 * ctx.padding -234 (ctx.dilation * (kernel_h - 1) + 1)) // ctx.stride + 1235 width_out = (width + 2 * ctx.padding -236 (ctx.dilation * (kernel_w - 1) + 1)) // ctx.stride + 1237 return n, channels_out, height_out, width_out238deform_conv = DeformConvFunction.apply...
TextConverters.py
Source:TextConverters.py
1import discord, asyncio, random, time, datetime, binascii2from discord.ext import commands3from discord.ext.commands import clean_content4class TextConverters(commands.Cog):5 def __init__(self, bot):6 self.bot = bot7 @commands.command(aliases=['mock'])8 async def drunkify(self, ctx, *, s):9 lst = [str.upper, str.lower]10 newText = await commands.clean_content().convert(ctx, ''.join(random.choice(lst)(c) for c in s))11 if len(newText) <= 380:12 await ctx.send(newText)13 else:14 try:15 await ctx.author.send(newText)16 await ctx.send(f"**{ctx.author.mention} The output too was too large, so I sent it to your DMs! :mailbox_with_mail:**")17 except Exception:18 await ctx.send(f"**{ctx.author.mention} There was a problem, and I could not send the output. It may be too large or malformed**")19 @commands.command()20 async def expand(self, ctx, num: int, *, s: clean_content):21 spacing = ""22 if num > 0 and num <= 5:23 for _ in range(num):24 spacing+=" "25 result = spacing.join(s)26 if len(result) <= 200:27 await ctx.send(result)28 else:29 try:30 await ctx.author.send(result)31 await ctx.send(f"**{ctx.author.mention} The output too was too large, so I sent it to your DMs! :mailbox_with_mail:**")32 except Exception:33 await ctx.send(f"**{ctx.author.mention} There was a problem, and I could not send the output. It may be too large or malformed**")34 else:35 await ctx.send("```fix\nError: The number can only be from 1 to 5```")36 @commands.command()37 async def reverse(self, ctx, *, s: clean_content):38 result = await commands.clean_content().convert(ctx, s[::-1])39 if len(result) <= 350:40 await ctx.send(f"{result}")41 else:42 try:43 await ctx.author.send(f"{result}")44 await ctx.send(f"**{ctx.author.mention} The output too was too large, so I sent it to your DMs! :mailbox_with_mail:**")45 except Exception:46 await ctx.send(f"**{ctx.author.mention} There was a problem, and I could not send the output. It may be too large or malformed**")47 @commands.command()48 async def texttohex(self, ctx, *, s):49 try:50 hexoutput = await commands.clean_content().convert(ctx, (" ".join("{:02x}".format(ord(c)) for c in s)))51 except Exception as e:52 await ctx.send(f"**Error: `{e}`. This probably means the text is malformed. Sorry, you can always try here: http://www.unit-conversion.info/texttools/hexadecimal/#data**")53 if len(hexoutput) <= 479:54 await ctx.send(f"```fix\n{hexoutput}```")55 else:56 try:57 await ctx.author.send(f"```fix\n{hexoutput}```")58 await ctx.send(f"**{ctx.author.mention} The output too was too large, so I sent it to your DMs! :mailbox_with_mail:**")59 except Exception:60 await ctx.send(f"**{ctx.author.mention} There was a problem, and I could not send the output. It may be too large or malformed**")61 @commands.command()62 async def hextotext(self, ctx, *, s):63 try:64 cleanS = await commands.clean_content().convert(ctx, bytearray.fromhex(s).decode())65 except Exception as e:66 await ctx.send(f"**Error: `{e}`. This probably means the text is malformed. Sorry, you can always try here: http://www.unit-conversion.info/texttools/hexadecimal/#data**")67 if len(cleanS) <= 479:68 await ctx.send(f"```{cleanS}```")69 else:70 try:71 await ctx.author.send(f"```{cleanS}```")72 await ctx.send(f"**{ctx.author.mention} The output too was too large, so I sent it to your DMs! :mailbox_with_mail:**")73 except Exception:74 await ctx.send(f"**{ctx.author.mention} There was a problem, and I could not send the output. It may be too large or malformed**")75 @commands.command()76 async def texttobinary(self, ctx, *, s):77 try:78 cleanS = await commands.clean_content().convert(ctx, ' '.join(format(ord(x), 'b') for x in s))79 except Exception as e:80 await ctx.send(f"**Error: `{e}`. This probably means the text is malformed. Sorry, you can always try here: http://www.unit-conversion.info/texttools/convert-text-to-binary/#data**")81 if len(cleanS) <= 479:82 await ctx.send(f"```fix\n{cleanS}```")83 else:84 try:85 await ctx.author.send(f"```fix\n{cleanS}```")86 await ctx.send(f"**{ctx.author.mention} The output too was too large, so I sent it to your DMs! :mailbox_with_mail:**")87 except Exception:88 await ctx.send(f"**{ctx.author.mention} There was a problem, and I could not send the output. It may be too large or malformed**")89 @commands.command()90 async def binarytotext(self, ctx, *, s):91 try:92 cleanS = await commands.clean_content().convert(ctx, ''.join([chr(int(s, 2)) for s in s.split()]))93 except Exception as e:94 await ctx.send(f"**Error: `{e}`. This probably means the text is malformed. Sorry, you can always try here: http://www.unit-conversion.info/texttools/convert-text-to-binary/#data**")95 if len(cleanS) <= 479:96 await ctx.send(f"```{cleanS}```")97 else:98 try:99 await ctx.author.send(f"```{cleanS}```")100 await ctx.send(f"**{ctx.author.mention} The output too was too large, so I sent it to your DMs! :mailbox_with_mail:**")101 except Exception:102 await ctx.send(f"**{ctx.author.mention} There was a problem, and I could not send the output. It may be too large or malformed**")103 @commands.group()104 async def specrypt(self, ctx):105 if ctx.invoked_subcommand is None:106 await ctx.send("```fix\nInvalid input. Please use one of the following:\nencrypt (e)\ndecrypt (d)\n\nExample: $specrypt e Hello world!```")107 @specrypt.command(aliases=['e'])108 async def encrypt(self, ctx, *, s):109 a = ''110 try:111 for letter in s:112 a+=chr(ord(letter)+len(s))113 cleanS = await commands.clean_content().convert(ctx, a)114 except Exception as e:115 await ctx.send(f"**Error: `{e}`. This probably means the input is malformed. Sorry, I'm not perfect and my creator is dumb**")116 if len(cleanS) <= 479:117 await ctx.send(f"```{cleanS}```")118 else:119 try:120 await ctx.author.send(f"```{cleanS}```")121 await ctx.send(f"**{ctx.author.mention} The output too was too large, so I sent it to your DMs! :mailbox_with_mail:**")122 except Exception:123 await ctx.send(f"**{ctx.author.mention} There was a problem, and I could not send the output. It may be too large or malformed**")124 @specrypt.command(aliases=['d'])125 async def decrypt(self, ctx, *, s):126 a = ''127 try:128 for letter in s:129 a+=chr(ord(letter)-len(s))130 cleanS = await commands.clean_content().convert(ctx, a)131 except Exception as e:132 await ctx.send(f"**Error: `{e}`. This probably means the input is malformed. Sorry, I'm not perfect and my creator is dumb**")133 if len(cleanS) <= 479:134 await ctx.send(f"```{cleanS}```")135 else:136 try:137 await ctx.author.send(f"```{cleanS}```")138 await ctx.send(f"**{ctx.author.mention} The output too was too large, so I sent it to your DMs! :mailbox_with_mail:**")139 except Exception:140 await ctx.send(f"**{ctx.author.mention} There was a problem, and I could not send the output. It may be too large or malformed**")141def setup(bot):...
functions.py
Source:functions.py
1from os import path2import torch 3import torch.distributed as dist4import torch.autograd as autograd5import torch.cuda.comm as comm6from torch.autograd.function import once_differentiable7from torch.utils.cpp_extension import load8_src_path = path.join(path.dirname(path.abspath(__file__)), "src")9_backend = load(name="inplace_abn",10 extra_cflags=["-O3"],11 sources=[path.join(_src_path, f) for f in [12 "inplace_abn.cpp",13 "inplace_abn_cpu.cpp",14 "inplace_abn_cuda.cu",15 "inplace_abn_cuda_half.cu"16 ]],17 extra_cuda_cflags=["--expt-extended-lambda"])18# Activation names19ACT_RELU = "relu"20ACT_LEAKY_RELU = "leaky_relu"21ACT_ELU = "elu"22ACT_NONE = "none"23def _check(fn, *args, **kwargs):24 success = fn(*args, **kwargs)25 if not success:26 raise RuntimeError("CUDA Error encountered in {}".format(fn))27def _broadcast_shape(x):28 out_size = []29 for i, s in enumerate(x.size()):30 if i != 1:31 out_size.append(1)32 else:33 out_size.append(s)34 return out_size35def _reduce(x):36 if len(x.size()) == 2:37 return x.sum(dim=0)38 else:39 n, c = x.size()[0:2]40 return x.contiguous().view((n, c, -1)).sum(2).sum(0)41def _count_samples(x):42 count = 143 for i, s in enumerate(x.size()):44 if i != 1:45 count *= s46 return count47def _act_forward(ctx, x):48 if ctx.activation == ACT_LEAKY_RELU:49 _backend.leaky_relu_forward(x, ctx.slope)50 elif ctx.activation == ACT_ELU:51 _backend.elu_forward(x)52 elif ctx.activation == ACT_NONE:53 pass54def _act_backward(ctx, x, dx):55 if ctx.activation == ACT_LEAKY_RELU:56 _backend.leaky_relu_backward(x, dx, ctx.slope)57 elif ctx.activation == ACT_ELU:58 _backend.elu_backward(x, dx)59 elif ctx.activation == ACT_NONE:60 pass61class InPlaceABN(autograd.Function):62 @staticmethod63 def forward(ctx, x, weight, bias, running_mean, running_var,64 training=True, momentum=0.1, eps=1e-05, activation=ACT_LEAKY_RELU, slope=0.01):65 # Save context66 ctx.training = training67 ctx.momentum = momentum68 ctx.eps = eps69 ctx.activation = activation70 ctx.slope = slope71 ctx.affine = weight is not None and bias is not None72 # Prepare inputs73 count = _count_samples(x)74 x = x.contiguous()75 weight = weight.contiguous() if ctx.affine else x.new_empty(0)76 bias = bias.contiguous() if ctx.affine else x.new_empty(0)77 if ctx.training:78 mean, var = _backend.mean_var(x)79 # Update running stats80 running_mean.mul_((1 - ctx.momentum)).add_(ctx.momentum * mean)81 running_var.mul_((1 - ctx.momentum)).add_(ctx.momentum * var * count / (count - 1))82 # Mark in-place modified tensors83 ctx.mark_dirty(x, running_mean, running_var)84 else:85 mean, var = running_mean.contiguous(), running_var.contiguous()86 ctx.mark_dirty(x)87 # BN forward + activation88 _backend.forward(x, mean, var, weight, bias, ctx.affine, ctx.eps)89 _act_forward(ctx, x)90 # Output91 ctx.var = var92 ctx.save_for_backward(x, var, weight, bias)93 return x94 @staticmethod95 @once_differentiable96 def backward(ctx, dz):97 z, var, weight, bias = ctx.saved_tensors98 dz = dz.contiguous()99 # Undo activation100 _act_backward(ctx, z, dz)101 if ctx.training:102 edz, eydz = _backend.edz_eydz(z, dz, weight, bias, ctx.affine, ctx.eps)103 else:104 # TODO: implement simplified CUDA backward for inference mode105 edz = dz.new_zeros(dz.size(1))106 eydz = dz.new_zeros(dz.size(1))107 dx = _backend.backward(z, dz, var, weight, bias, edz, eydz, ctx.affine, ctx.eps)108 dweight = eydz * weight.sign() if ctx.affine else None109 dbias = edz if ctx.affine else None110 return dx, dweight, dbias, None, None, None, None, None, None, None111class InPlaceABNSync(autograd.Function):112 @classmethod113 def forward(cls, ctx, x, weight, bias, running_mean, running_var,114 training=True, momentum=0.1, eps=1e-05, activation=ACT_LEAKY_RELU, slope=0.01, equal_batches=True):115 # Save context116 ctx.training = training117 ctx.momentum = momentum118 ctx.eps = eps119 ctx.activation = activation120 ctx.slope = slope121 ctx.affine = weight is not None and bias is not None122 # Prepare inputs123 ctx.world_size = dist.get_world_size() if dist.is_initialized() else 1124 #count = _count_samples(x)125 batch_size = x.new_tensor([x.shape[0]],dtype=torch.long)126 x = x.contiguous()127 weight = weight.contiguous() if ctx.affine else x.new_empty(0)128 bias = bias.contiguous() if ctx.affine else x.new_empty(0)129 if ctx.training:130 mean, var = _backend.mean_var(x)131 if ctx.world_size>1:132 # get global batch size133 if equal_batches:134 batch_size *= ctx.world_size135 else:136 dist.all_reduce(batch_size, dist.ReduceOp.SUM)137 ctx.factor = x.shape[0]/float(batch_size.item())138 mean_all = mean.clone() * ctx.factor139 dist.all_reduce(mean_all, dist.ReduceOp.SUM)140 var_all = (var + (mean - mean_all) ** 2) * ctx.factor141 dist.all_reduce(var_all, dist.ReduceOp.SUM)142 mean = mean_all143 var = var_all144 # Update running stats145 running_mean.mul_((1 - ctx.momentum)).add_(ctx.momentum * mean)146 count = batch_size.item() * x.view(x.shape[0],x.shape[1],-1).shape[-1]147 running_var.mul_((1 - ctx.momentum)).add_(ctx.momentum * var * (float(count) / (count - 1)))148 # Mark in-place modified tensors149 ctx.mark_dirty(x, running_mean, running_var)150 else:151 mean, var = running_mean.contiguous(), running_var.contiguous()152 ctx.mark_dirty(x)153 # BN forward + activation154 _backend.forward(x, mean, var, weight, bias, ctx.affine, ctx.eps)155 _act_forward(ctx, x)156 # Output157 ctx.var = var158 ctx.save_for_backward(x, var, weight, bias)159 return x160 @staticmethod161 @once_differentiable162 def backward(ctx, dz):163 z, var, weight, bias = ctx.saved_tensors164 dz = dz.contiguous()165 # Undo activation166 _act_backward(ctx, z, dz)167 if ctx.training:168 edz, eydz = _backend.edz_eydz(z, dz, weight, bias, ctx.affine, ctx.eps)169 edz_local = edz.clone()170 eydz_local = eydz.clone()171 if ctx.world_size>1:172 edz *= ctx.factor173 dist.all_reduce(edz, dist.ReduceOp.SUM)174 eydz *= ctx.factor175 dist.all_reduce(eydz, dist.ReduceOp.SUM)176 else:177 edz_local = edz = dz.new_zeros(dz.size(1))178 eydz_local = eydz = dz.new_zeros(dz.size(1))179 dx = _backend.backward(z, dz, var, weight, bias, edz, eydz, ctx.affine, ctx.eps)180 dweight = eydz_local * weight.sign() if ctx.affine else None181 dbias = edz_local if ctx.affine else None182 return dx, dweight, dbias, None, None, None, None, None, None, None183inplace_abn = InPlaceABN.apply184inplace_abn_sync = InPlaceABNSync.apply...
roi_pool.py
Source:roi_pool.py
1import torch2from torch.autograd import Function3from .._ext import roi_pooling4import pdb5class RoIPoolFunction(Function):6 def __init__(ctx, pooled_height, pooled_width, spatial_scale):7 ctx.pooled_width = pooled_width8 ctx.pooled_height = pooled_height9 ctx.spatial_scale = spatial_scale10 ctx.feature_size = None11 def forward(ctx, features, rois): 12 ctx.feature_size = features.size() 13 batch_size, num_channels, data_height, data_width = ctx.feature_size14 num_rois = rois.size(0)15 output = features.new(num_rois, num_channels, ctx.pooled_height, ctx.pooled_width).zero_()16 ctx.argmax = features.new(num_rois, num_channels, ctx.pooled_height, ctx.pooled_width).zero_().int()17 ctx.rois = rois18 if not features.is_cuda:19 _features = features.permute(0, 2, 3, 1)20 roi_pooling.roi_pooling_forward(ctx.pooled_height, ctx.pooled_width, ctx.spatial_scale,21 _features, rois, output)22 else:23 roi_pooling.roi_pooling_forward_cuda(ctx.pooled_height, ctx.pooled_width, ctx.spatial_scale,24 features, rois, output, ctx.argmax)25 return output26 def backward(ctx, grad_output):27 assert(ctx.feature_size is not None and grad_output.is_cuda)28 batch_size, num_channels, data_height, data_width = ctx.feature_size29 grad_input = grad_output.new(batch_size, num_channels, data_height, data_width).zero_()30 roi_pooling.roi_pooling_backward_cuda(ctx.pooled_height, ctx.pooled_width, ctx.spatial_scale,31 grad_output, ctx.rois, grad_input, ctx.argmax)...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.runTest(pageToTest, function(err, data) {4 if (err) return console.log(err);5 wpt.getTestResults(data.data.testId, function(err, data) {6 if (err) return console.log(err);7 console.log(data);8 });9});
Using AI Code Generation
1const wpt = require('webpagetest');2const wptClient = wpt('www.webpagetest.org');3 videoParams: {4 },5}, (err, data) => {6 if (err) {7 console.error(err);8 }9 console.log(data);10});11const wpt = require('webpagetest');12const wptClient = wpt('www.webpagetest.org');13 videoParams: {14 },15}, (err, data) => {16 if (err) {17 console.error(err);18 }19 console.log(data);20});21const wpt = require('webpagetest');22const wptClient = wpt('www.webpagetest.org');23 videoParams: {24 },25}, (err, data) => {26 if (err) {27 console.error(err);28 }29 console.log(data);30});31const wpt = require('webpagetest');32const wptClient = wpt('www.webpagetest.org');
Using AI Code Generation
1module.exports = async function(ctx) {2 await ctx.method1();3 await ctx.method2();4 await ctx.method3();5 await ctx.method4();6 await ctx.method5();7 await ctx.method6();8 await ctx.method7();9 await ctx.method8();10 await ctx.method9();11 await ctx.method10();12};13module.exports = async function(ctx) {14 await ctx.method1();15 await ctx.method2();16 await ctx.method3();17 await ctx.method4();18 await ctx.method5();19 await ctx.method6();20 await ctx.method7();21 await ctx.method8();22 await ctx.method9();23 await ctx.method10();24};25module.exports = async function(ctx) {26 await ctx.method1();27 await ctx.method2();28 await ctx.method3();29 await ctx.method4();30 await ctx.method5();31 await ctx.method6();32 await ctx.method7();33 await ctx.method8();34 await ctx.method9();35 await ctx.method10();36};37module.exports = async function(ctx) {38 await ctx.method1();39 await ctx.method2();40 await ctx.method3();41 await ctx.method4();42 await ctx.method5();43 await ctx.method6();44 await ctx.method7();45 await ctx.method8();46 await ctx.method9();47 await ctx.method10();48};49module.exports = async function(ctx) {50 await ctx.method1();51 await ctx.method2();52 await ctx.method3();53 await ctx.method4();54 await ctx.method5();55 await ctx.method6();56 await ctx.method7();57 await ctx.method8();58 await ctx.method9();59 await ctx.method10();60};61module.exports = async function(ctx) {62 await ctx.method1();63 await ctx.method2();64 await ctx.method3();65 await ctx.method4();66 await ctx.method5();67 await ctx.method6();68 await ctx.method7();69 await ctx.method8();70 await ctx.method9();71 await ctx.method10();72};
Using AI Code Generation
1ctx.setCookie({2});3ctx.setCookie({4});5ctx.setCookie({6});7ctx.setCookie({8});9ctx.setCookie({10});11ctx.setCookie({12});13ctx.setCookie({14});15ctx.setCookie({16});17ctx.setCookie({
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.9b9d7c7e6d0c1e1b2728a8e1d3d3e3f3');3wpt.getTestResults('160702_6P_3c2a2f1f2f7d0e5b5e5c5a8e5c5d5a5e', function(err, data) {4 console.log(data);5});6var wpt = require('webpagetest');7var wpt = new WebPageTest('www.webpagetest.org', 'A.9b9d7c7e6d0c1e1b2728a8e1d3d3e3f3');8wpt.getTestResults('160702_6P_3c2a2f1f2f7d0e5b5e5c5a8e5c5d5a5e', function(err, data) {9 console.log(data);10});11var wpt = require('webpagetest');12var wpt = new WebPageTest('www.webpagetest.org', 'A.9b9d7c7e6d0c1e1b2728a8e1d3d3e3f3');13wpt.getTestResults('160702_6P_3c2a2f1f2f7d0e5b5e5c5a8e5c5d5a5e', function(err, data) {14 console.log(data);15});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!