How to use viewport_size method in Playwright Python

Best Python code snippet using playwright-python

runes.py

Source:runes.py Github

copy

Full Screen

1def is_list(lst):2 return isinstance(lst, (list, tuple))3# Constants4viewport_size = 600 # This is the height of the viewport5spread = 20 #used to be 20, but i like at 806active_hollusion = None7lastframe = None8#Setup9import graphics10import math11import time12import PyGif13Posn = graphics.Posn14Rgb = graphics.Rgb15draw_solid_polygon = graphics.draw_solid_polygon16graphics.init(viewport_size)17vp = graphics.open_viewport("ViewPort", 4/3*viewport_size, viewport_size)18lp = graphics.open_pixmap("LeftPort", 4/3*viewport_size, viewport_size)19rp = graphics.open_pixmap("RightPort", 4/3*viewport_size, viewport_size)20def clear_all():21 global active_hollusion22 global vp, lp, rp23 if(active_hollusion != None):24 active_hollusion("kill")25 active_hollusion = None26 graphics.clear_viewport(vp)27 graphics.clear_viewport(lp)28 graphics.clear_viewport(rp)29class Frame:30 def __init__(self, p0, p1, p2, z1, z2):31 self.orig = p032 self.x = p133 self.y = p234 self.z1 = z135 self.z2 = z236unit_frame = Frame(Posn(1/6*viewport_size, 0),37 Posn(viewport_size,0),38 Posn(0,viewport_size),39 0,40 1)41def show(painter):42 return painter(vp, unit_frame)43def scale_vect(mult, p):44 return Posn(mult*p.x, mult*p.y)45#translate_posn removed - no one uses it.46 #Also it only translates on x axis47def transform_posn(frame):48 def f(posn):49 return frame.orig + (scale_vect(posn.x/viewport_size, frame.x) + scale_vect(posn.y/viewport_size, frame.y))50 return f51#this is new - for higher precision rendering52def inverse_transform_posn(frame):53 a = frame.x.x54 b = frame.y.x55 c = frame.x.y56 d = frame.y.y57 det = a*d-b*c58 if(det == 0):59 raise Exception("somehow you managed to zero the determinent for your frame")60 inv_mat = ((d/det, -b/det), (-c/det, a/det))61 def function(posn):62 nonlocal inv_mat63 t = list(map(lambda m: m[0]*(posn.x-frame.orig.x) + m[1] * (posn.y-frame.orig.y), inv_mat)) #it's a matrix multiply64 return Posn(viewport_size*t[0], viewport_size*t[1])65 return function66##painters67def blank_bb(vp, frame):68 return69def sail_bb(vp, frame):70 p = [Posn(viewport_size/2, 0), Posn(viewport_size/2, viewport_size), Posn(viewport_size, viewport_size)]71 if(is_list(vp[0])):72 for count, port in enumerate(vp):73 draw_solid_polygon(port, map(transform_posn(frame), p),74 Posn((0.3 - frame.z1) * (spread * (((2 * count) / (len(vp) - 1)) - 1)), 0),75 Rgb(frame.z1, frame.z1, frame.z1))76 elif (vp != None):77 draw_solid_polygon(vp, map(transform_posn(frame), p), Posn(0,0), Rgb(frame.z1, frame.z1, frame.z1))78def corner_bb(vp, frame):79 p = [Posn(viewport_size/2, 0), Posn(viewport_size,0), Posn(viewport_size, viewport_size/2)]80 if(is_list(vp[0])):81 for count, port in enumerate(vp):82 draw_solid_polygon(port, map(transform_posn(frame), p),83 Posn((0.3 - frame.z1) * (spread * (((2 * count) / (len(vp) - 1)) - 1)), 0),84 Rgb(frame.z1, frame.z1, frame.z1))85 elif (vp != None):86 draw_solid_polygon(vp, map(transform_posn(frame), p), Posn(0,0), Rgb(frame.z1, frame.z1, frame.z1))87def black_bb(vp, frame):88 p = [Posn(0,0), Posn(viewport_size,0), Posn(viewport_size, viewport_size), Posn(0, viewport_size)]89 if(is_list(vp[0])):90 for count, port in enumerate(vp):91 draw_solid_polygon(port, map(transform_posn(frame), p),92 Posn((0.3 - frame.z1) * (spread * (((2 * count) / (len(vp) - 1)) - 1)), 0),93 Rgb(frame.z1, frame.z1, frame.z1))94 elif (vp != None):95 draw_solid_polygon(vp, map(transform_posn(frame), p), Posn(0,0), Rgb(frame.z1, frame.z1, frame.z1))96# // center-and-fill will center and scale a 2x2 image to fill the entire viewport.97# // This is used by circle-bb, spiral-bb, and ribbon-bb.98def center_and_fill(p):99 center = Posn(viewport_size/2,viewport_size/2)100 return center+scale_vect(viewport_size/2, p)101#same with the js version, this doesn't work.102def spiral_bb(vp, frame):103 theta_max = 30104 thickness = -1/theta_max105 offset = 0.1106 angle = 0107 p = []108 while(angle<theta_max):109 p.append(Posn( (offset+angle/theta_max)*math.cos(angle) , (offset+angle/theta_max)*math.sin(angle)))110 angle += offset111 if(is_list(vp[0])):112 for count, port in enumerate(vp):113 draw_solid_polygon(port, map(transform_posn(frame), map(center_and_fill, p)),114 Posn((0.3 - frame.z1) * (spread * (((2 * count) / (len(vp) - 1)) - 1)), 0),115 Rgb(frame.z1, frame.z1, frame.z1))116 elif (vp != None):117 draw_solid_polygon(vp, map(transform_posn(frame), map(center_and_fill, p)), Posn(0,0), Rgb(frame.z1, frame.z1, frame.z1))118def circle_bb(vp, frame):119 unit = 50120 p = []121 angle = 0122 while(angle<2*math.pi):123 p.append(Posn(math.cos(angle),math.sin(angle)))124 angle+= unit/viewport_size125 if(is_list(vp[0])):126 for count, port in enumerate(vp):127 draw_solid_polygon(port, map(transform_posn(frame), map(center_and_fill, p)),128 Posn((0.3 - frame.z1) * (spread * (((2 * count) / (len(vp) - 1)) - 1)), 0),129 Rgb(frame.z1, frame.z1, frame.z1))130 elif (vp != None):131 draw_solid_polygon(vp, map(transform_posn(frame), map(center_and_fill, p)), Posn(0,0), Rgb(frame.z1, frame.z1, frame.z1))132def pentagram_bb(vp, frame):133 unit_offset = viewport_size / 2134 s1 = math.sin(2*math.pi/5) * unit_offset135 c1 = math.cos(2*math.pi/5) * unit_offset136 s2 = math.sin(4*math.pi/5) * unit_offset137 c2 = math.cos(math.pi/5) * unit_offset138 a = s2 / (s1 + s2)139 a_ = 1-a140 p = [Posn(-s1 + unit_offset, -c1 + unit_offset),\141 Posn(s1+unit_offset, -c1 + unit_offset),\142 Posn(-s2+unit_offset, c2+unit_offset),\143 Posn(unit_offset, 0),\144 Posn(s2+unit_offset, c2+unit_offset)145 ]146 #converted to 10 element form.147 p = [p[0],\148 p[3]*a+p[2]*a_,\149 p[2],\150 p[1]*a+p[2]*a_,\151 p[4],\152 p[2]*a+p[1]*a_,\153 p[1],\154 p[4]*a+p[3]*a_,\155 p[3],\156 p[2]*a+p[3]*a_]157 if(is_list(vp[0])):158 for count, port in enumerate(vp):159 draw_solid_polygon(port, map(transform_posn(frame), p),160 Posn((0.3 - frame.z1) * (spread * (((2 * count) / (len(vp) - 1)) - 1)), 0),161 Rgb(frame.z1, frame.z1, frame.z1))162 elif (vp != None):163 draw_solid_polygon(vp, map(transform_posn(frame), p), Posn(0,0), Rgb(frame.z1, frame.z1, frame.z1))164def heart_bb(vp, frame):165 k = math.sqrt(2)/2166 p = [Posn(viewport_size/2, (1-k)/(1+3*k) * viewport_size),\167 Posn((1-k)/(1+k) * viewport_size / 2, (1+k)/(1+3*k) * viewport_size),\168 Posn(viewport_size / 2, viewport_size),\169 Posn(viewport_size - (1-k)/(1+k) * viewport_size / 2, (1+k)/(1+3*k) * viewport_size)]170 #draws kite171 if(is_list(vp[0])):172 for count, port in enumerate(vp):173 draw_solid_polygon(port, map(transform_posn(frame), p),174 Posn((0.3 - frame.z1) * (spread * (((2 * count) / (len(vp) - 1)) - 1)), 0),175 Rgb(frame.z1, frame.z1, frame.z1))176 elif (vp != None):177 draw_solid_polygon(vp, map(transform_posn(frame), p), Posn(0,0), Rgb(frame.z1, frame.z1, frame.z1))178 #Draw the top of the heart179 heart_circle = stack_frac(2 / (1 + 3 * k), \180 quarter_turn_right(stack_frac(k / (1+k), blank_bb, circle_bb)), \181 blank_bb)182 heart_circle(vp, frame)183 flip_horiz(heart_circle)(vp, frame)184def rcross_bb(vp, frame):185 p1 = [Posn(0,0),\186 Posn(viewport_size / 4, viewport_size / 4),\187 Posn(3 * viewport_size / 4, viewport_size / 4),\188 Posn(3 * viewport_size / 4, 3 * viewport_size / 4),\189 Posn(viewport_size, viewport_size),\190 Posn(viewport_size, 0)]191 p2 = [Posn(viewport_size / 4, viewport_size / 4),\192 Posn(viewport_size / 4, 3 * viewport_size / 4),\193 Posn(3 * viewport_size / 4, 3 * viewport_size / 4)]194 if(is_list(vp[0])):195 for count, port in enumerate(vp):196 draw_solid_polygon(port, map(transform_posn(frame), p1),197 Posn((0.3 - frame.z1) * (spread * (((2 * count) / (len(vp) - 1)) - 1)), 0),198 Rgb(frame.z1, frame.z1, frame.z1))199 draw_solid_polygon(port, map(transform_posn(frame), p2),200 Posn((0.3 - frame.z1) * (spread * (((2 * count) / (len(vp) - 1)) - 1)), 0),201 Rgb(frame.z1, frame.z1, frame.z1))202 elif (vp != None):203 draw_solid_polygon(vp, map(transform_posn(frame), p1), Posn(0,0), Rgb(frame.z1, frame.z1, frame.z1))204 draw_solid_polygon(vp, map(transform_posn(frame), p2), Posn(0,0), Rgb(frame.z1, frame.z1, frame.z1))205def ribbon_bb(vp, frame):206 theta_max = 30207 thickness = -1 / theta_max208 unit = 0.1209 p = []210 angle = 0211 #make ribbon212 while(angle<theta_max):213 p.append(Posn((angle / theta_max) * math.cos(angle), \214 (angle / theta_max) * math.sin(angle)))215 angle+= unit216 #close it217 while(angle>0):218 p.append(Posn(abs(math.cos(angle) * thickness) + (angle / theta_max * math.cos(angle)),\219 abs(math.sin(angle) * thickness) + (angle / theta_max * math.sin(angle))))220 angle -= unit221 if(is_list(vp[0])):222 for count, port in enumerate(vp):223 draw_solid_polygon(port, map(transform_posn(frame), map(center_and_fill, p)),224 Posn((0.3 - frame.z1) * (spread * (((2 * count) / (len(vp) - 1)) - 1)), 0),225 Rgb(frame.z1, frame.z1, frame.z1))226 elif (vp != None):227 draw_solid_polygon(vp, map(transform_posn(frame), map(center_and_fill, p)), Posn(0,0), Rgb(frame.z1, frame.z1, frame.z1))228def nova_bb(vp, frame):229 p = [Posn(viewport_size / 2, 0),\230 Posn(viewport_size / 4, viewport_size / 2),\231 Posn(viewport_size, viewport_size / 2),\232 Posn(viewport_size / 2, viewport_size / 4)]233 if(is_list(vp[0])):234 for count, port in enumerate(vp):235 draw_solid_polygon(port, map(transform_posn(frame), p),236 Posn((0.3 - frame.z1) * (spread * (((2 * count) / (len(vp) - 1)) - 1)), 0),237 Rgb(frame.z1, frame.z1, frame.z1))238 elif (vp != None):239 draw_solid_polygon(vp, map(transform_posn(frame), p), Posn(0,0), Rgb(frame.z1, frame.z1, frame.z1))240#frame transformation factory241def process_frame(op, frame):242 p0 = frame.orig243 p1 = frame.x244 p2 = frame.y245 z1 = frame.z1246 z2 = frame.z2247 if (op == "bottom_frac"):248 def function(frac):249 return Frame(p0 + scale_vect(1 - frac, p2), p1, scale_vect(frac, p2), z1, z2)250 return function251 elif (op == "top_frac"):252 def function(frac):253 return Frame(p0, p1, scale_vect(frac, p2), z1, z2)254 return function255 #unused256 elif (op == "left"):257 return Frame(p0, scale_vect(1/2, p1), p2, z1, z2)258 #unused259 elif (op == "right"):260 return Frame(p0+scale_vect(1/2, p1), scale_vect(1/2, p1), p2, z1, z2)261 elif (op == "flip_horiz"):262 return Frame(p0+p1, scale_vect(-1, p1), p2, z1, z2)263 elif (op == "flip_vert"):264 return Frame(p0+p2, p1, scale_vect(-1, p2), z1, z2)265 elif (op == "reduce_2"): # unused in original266 raise NotImplementedError("reduce_2 is not implemented")267 elif (op == "rotate"): #bug: Basically old rotate bug.268 def function(rad):269 cos_theta = math.cos(rad)270 sin_theta = math.sin(rad)271 def rotate_posn(p):272 return Posn(cos_theta*p.x + sin_theta * p.y, cos_theta * p.y - sin_theta * p.x)273 half_gradient = scale_vect(1/2, p1+p2)274 center = p0+half_gradient+ rotate_posn(scale_vect(-1, half_gradient))275 return Frame(center, rotate_posn(p1), rotate_posn(p2), z1, z2)276 return function277 elif (op == "rotate90"):278 return Frame(p0+p1, p2, scale_vect(-1, p1), z1, z2)279 elif (op == "deep_frac"):280 def function(frac):281 return Frame(p0, p1, p2, z1+((z2-z1)*frac),z2)282 return function283 elif (op == "shallow_frac"):284 def function(frac):285 return Frame(p0, p1, p2, z1, z1+((z2-z1)*frac))286 return function287 elif (op == "scale_independent"):288 def function(ratio_x, ratio_y):289 gradient = p1+p2290 scaled_gradient = Posn(((1-ratio_x)/2)* gradient.x, ((1-ratio_y)/2)*gradient.y)291 center = p0+scaled_gradient292 return Frame(center, scale_vect(ratio_x, p1), scale_vect(ratio_y, p2), z1, z2)293 return function294 elif (op == "translate"):295 def function(x,y):296 return Frame(p0+scale_vect(x,p1)+scale_vect(y,p2), p1,p2,z1,z2)297 return function298##basic painter combinations299#top, bottom300def stack_frac(frac, p1, p2):301 def function(vp, frame):302 uf = process_frame("top_frac", frame)(frac)303 lf = process_frame("bottom_frac", frame)(1-frac)304 p1(vp, uf)305 p2(vp, lf)306 return function307#top, bottom308def stack(p1, p2):309 return stack_frac(1/2, p1, p2)310def rotate(rad, painter):311 def function(vp, frame):312 painter(vp, process_frame("rotate", frame)(rad))313 return function314def eighth_turn_left(painter):315 return rotate(math.pi/4, painter)316def quarter_turn_right(painter):317 def function(vp, frame):318 painter(vp, process_frame("rotate90", frame))319 return function320def flip_vert(painter):321 def function(vp, frame):322 painter(vp, process_frame("flip_vert", frame))323 return function324def flip_horiz(painter):325 def function(vp, frame):326 painter(vp, process_frame("flip_horiz", frame))327 return function328#TODO: rewrite overlay consistently329#p1 over p2330def overlay_frac(frac, p1, p2):331 def function(vp, frame):332 if(frac>1 or frac<0):333 raise ValueError("overlay_frac: 0 <= frac <= 1 is required")334 else:335 df = process_frame("deep_frac", frame)(frac)336 sf = process_frame("shallow_frac", frame)(frac)337 p2(vp, df)338 p1(vp, sf)339 return function340#p1 under p2341def overlay(p1, p2):342 return overlay_frac(1/2, p1, p2)343def scale_independent(ratio_x, ratio_y, painter):344 def function(vp, frame):345 painter(vp, process_frame("scale_independent", frame)(ratio_x, ratio_y))346 return function347def scale(ratio, painter):348 return scale_independent(ratio, ratio, painter)349# // Translate the painter. Note that positive x means right translate350# // positive y means translate down.351# the amount is to be a fraction of viewport_size352def translate(x,y, painter):353 def function(vp, frame):354 painter(vp, process_frame("translate", frame)(x,y))355 return function356#painter combinations defined in lecture 2357#check if this is still in lecture 2358def turn_upside_down(painter):359 return quarter_turn_right(quarter_turn_right(painter))360def quarter_turn_left(painter):361 return turn_upside_down(quarter_turn_right(painter))362def beside(painter1, painter2):363 return quarter_turn_right(stack(quarter_turn_left(painter2), quarter_turn_left(painter1)));364def make_cross(painter):365 return stack(beside(quarter_turn_right(painter), turn_upside_down(painter)), beside(painter,quarter_turn_left(painter)))366def repeat_pattern(n, pat, pic):367 if(n==0):368 return pic369 else:370 return pat(repeat_pattern(n-1, pat, pic))371def stackn(n, painter):372 if n==1:373 return painter374 else:375 return stack_frac(1/n, painter, stackn(n-1, painter))376def hollusion(painter, ports=None):377 global active_hollusion378 frequency = 2379 MAX_X = round(4/3*viewport_size)380 MAX_Y = round(viewport_size)381 num = ports382 if ports == None or ports <= 2:383 num = 9 #because python is faster than scheme. Used to be 3384 buffers = list(map(lambda p: graphics.open_pixmap("buffer", 4/3*viewport_size,viewport_size), range(num)))385 stereo = vp386 def animation(cmd=None):387 ports = buffers388 kill = False389 curr = -1390 dir = 1391 def Self(msg):392 nonlocal kill393 nonlocal curr394 nonlocal Self395 nonlocal dir396 if msg == "next":397 curr = (curr+dir)398 if (curr == num or curr<0):399 dir = -dir400 curr += 2*dir401 graphics.show_viewport(buffers[curr])402 if(kill != True): #moved it here so you can happily next if the hollusion is dead.403 vp[0].after(round(1000/(frequency * len(ports))), lambda: Self("next"))404 #Timer(1/(frequency * len(ports)), Self, args=["next"]).start() #doesn't work because not thread safe405 elif msg == "kill":406 kill = True407 elif msg == "buffer":408 return ports409 else:410 return411 return Self412 painter(buffers, unit_frame)413 if(active_hollusion != None):414 active_hollusion("kill")415 active_hollusion = animation()416 active_hollusion("next")417 return active_hollusion418def anaglyph(painter):419 if graphics.PIL_available:420 MAX_X = round(4/3*viewport_size)421 MAX_Y = viewport_size422 stereo = vp423 depth = graphics.open_pixmap("Depthmap Viewport", viewport_size, viewport_size)424 def get_depth(x,y, pix):425 return pix[x,y][0]426 painter([lp, rp], unit_frame)427 #really! if you use getdata(), you need to calculate the offset in the array428 #load() returns a "2d pixel array" or rather, whatever it returns acts like one for all intents and purposes429 lp_pix = graphics.get_pixels(lp)430 rp_pix = graphics.get_pixels(rp)431 pixels = graphics.get_pixels(stereo)432 for y in range(MAX_Y):433 for x in range(MAX_X):434 l = get_depth(x,y,lp_pix)435 r = get_depth(x,y,rp_pix)436 pixels[x,y] = (r,l,l)437 graphics.pixels_to_canvas(stereo)438 else:439 print("PIL does not appear to be available")440def function_to_painter(depth_fun):441 tolerance = 1/spread442 def get_depth(x, y, dir, frame): # lp -> dir = -1, rp -> dir = 1443 result = 1444 for c in range(0, spread):445 ox = round(x + (dir * ((-0.3 * spread) + c)))446 if (ox >= 0 and ox < viewport_size):447 curr = depth_fun(round(ox), round(y))448 if (curr != 1):449 curr = frame.z1 + ((frame.z2 - frame.z1) * curr)450 d = abs(curr - c/spread)451 if(d < tolerance):452 result = curr453 return result454 def painter(vp, frame):455 def ana_out_loop(port, count):456 inverse_transform = inverse_transform_posn(frame)457 tgtpixels = graphics.get_pixels(port)458 size = graphics.get_image_size(port)459 MAX_X = size[0]460 MAX_Y = size[1]461 tgtpixels = graphics.get_pixels(port)462 for y in range(MAX_Y):463 for x in range(MAX_X):464 posn = inverse_transform(Posn(x,y))465 col = get_depth(posn.x, posn.y, count, frame)466 if (col>1):467 col = 1468 col = round(col*255)469 if(col<255):470 #tgtpixels[x,y] = (col, col, col)471 tgtpixels[x,y] = (min(col, tgtpixels[x,y][0]), min(col, tgtpixels[x,y][1]), min(col, tgtpixels[x,y][2]))472 graphics.pixels_to_canvas(port)473 if(is_list(vp[0])):474 for count, port in enumerate(vp):475 ana_out_loop(port, ((2*count)/(len(vp)-1) - 1))476 else:477 inverse_transform = inverse_transform_posn(frame)478 tgtpixels = graphics.get_pixels(vp)479 size = graphics.get_image_size(vp)480 MAX_X = size[0]481 MAX_Y = size[1]482 for y in range(MAX_Y):483 for x in range(MAX_X):484 posn = inverse_transform(Posn(x,y))485 color = depth_fun(posn.x, posn.y)486 if(color != 1):487 color = frame.z1 + ((frame.z2 - frame.z1) * color)488 if (color>1):489 color = 1490 color = round(color*255)491 if(color<255): #assuming that white is the transparency color492 #tgtpixels[x,y] = (color, color, color)493 tgtpixels[x,y] = (min(color, tgtpixels[x,y][0]), min(color, tgtpixels[x,y][1]), min(color, tgtpixels[x,y][2]))494 graphics.pixels_to_canvas(vp)495 return painter496def image_to_painter(filename):497 img = graphics.load_image(filename)498 tolerance = 1/spread499 limit = 0.86500 #process501 def painter(vp, frame):502 if(is_list(vp[0])):503 def get_depth(x,y,dir):504 global spread505 nonlocal pixels506 for c in range(spread):507 ox = round(x+dir*(-0.3*spread+c))508 if(ox>=0 and ox<viewport_size):509 if type(pixels[ox,y]) is int: #this is a workaround for black/white pictures.510 curr = pixels[ox,y]511 else:512 curr = pixels[ox, y][0]513 d = abs(curr - 255*c/spread)514 if(d<=tolerance*255):515 return curr516 return 255517 def ana_out_loop(port, count):518 nonlocal img519 size = graphics.get_image_size(img)520 MAX_X = size[0]521 MAX_Y = size[1]522 tsize = graphics.get_image_size(port)523 TMAX_X = tsize[0]524 TMAX_Y = tsize[1]525 tgtpixels = graphics.get_pixels(port)526 inv_transform = inverse_transform_posn(frame)527 # for y in range(MAX_Y):528 # for x in range(MAX_X):529 # col = get_depth(x,y,count)530 # if(col>255*limit):531 # col = 999532 # else:533 # col = frame.z1 + (frame.z2 - frame.z1) * col534 # if col<=255:535 # transposn = transform(Posn(x,y))536 # if(transposn.x>=0 and transposn.y>=0 and transposn.x<TMAX_X and transposn.y<TMAX_Y):537 # tgtpixels[transposn.x, transposn.y] = (col,col,col)538 #sorry, no supersampling. Takes long enough as it is.539 for y in range(TMAX_Y):540 for x in range(TMAX_X):541 orig = inv_transform(Posn(x,y))542 rx = round(orig.x)543 ry = round(orig.y)544 if (rx>=0 and ry>=0 and rx<MAX_X and ry<MAX_Y): #within bounds545 col = get_depth(rx, ry, count)546 if(col>255*limit):547 col = 999548 else:549 col = round(frame.z1*255 + (frame.z2 - frame.z1) * col)550 if(col<=255):551 #tgtpixels[x,y] = (col, col, col)552 tgtpixels[x,y] = (min(col, tgtpixels[x,y][0]),min(col, tgtpixels[x,y][1]),min(col, tgtpixels[x,y][2]))553 graphics.pixels_to_canvas(port)554 pixels = graphics.get_pixels(img)555 for count, port in enumerate(vp):556 ana_out_loop(port, ((2*count)/(len(vp)-1) - 1))557 else:558 transform = inverse_transform_posn(frame)559 graphics.blit_pixels(vp, transform, graphics.get_pixels(img), graphics.get_image_size(vp), graphics.get_image_size(img), True, frame.z1, frame.z2) #block level image transfer560 return painter561from random import random562def stereogram(painter):563 E = 300 #distance between eyes in pixels564 D = 600 #distance between eyes and image plane in pixels565 delta = 40 #stereo separation566 MAX_X = round(4/3*viewport_size)567 MAX_Y = viewport_size568 MAX_Z = 0569 CENTRE = round(MAX_X/2)570 stereo = vp571 pixels = graphics.get_pixels(stereo)572 depthmap = graphics.open_pixmap("temp", 4/3*viewport_size, viewport_size)573 depth_pix = graphics.get_pixels(depthmap)574 painter(depthmap, unit_frame)575 Infinity = float("inf")576 depth_pix = graphics.get_pixels(depthmap)577 def get_depth(x,y):578 if((x>=(1/6*viewport_size)) and (x<(MAX_X-(1/6*viewport_size)))):579 return -100*depth_pix[x,y][0]/255 - 400580 else:581 return -500582 for y in range(MAX_Y):583 link_left = {}584 link_right = {}585 colours = {}586 for x in range(MAX_X):587 z = get_depth(x,y)588 s = delta + z*(E/(z-D)) #Determine distance between intersection of lines of sight on image589 left = x - round(s/2) #x is integer, left is integer590 right = left + round(s) #right is integer591 if (left>0 and right<MAX_X):592 if(( not(left in link_right) or s<link_right[left]) and (not(right in link_left) or s<link_left[right])):593 link_right[left] = round(s)594 link_left[right] = round(s)595 #constraint resolution596 for x in range(MAX_X):597 try:598 s = link_left[x]599 except KeyError:600 s = Infinity601 if(s != Infinity):602 s = x603 d = None604 if(x-s>0):605 d = link_right[x-s]606 else:607 d = Infinity608 if(s == Infinity or (s>d)):609 link_left[x] = 0610 #drawing step611 for x in range(MAX_X):612 s = link_left[x] #should be valid for [0, MAX_X-1]613 try:614 colour = colours[x-s]615 except KeyError:616 colour = (round(random()*10/9*255),round(random()*10/9*255),round(random()*10/9*255))617 pixels[x,y] = colour618 colours[x] = colour619 graphics.pixels_to_canvas(stereo)620def save_image(filename):621 graphics.saveImage(vp, filename)622def save_hollusion(filename):623 if graphics.PIL_available:624 if active_hollusion == None:625 raise("No hollusion active")626 else:627 filename += ".gif"628 frames = list(map(lambda vp: graphics.get_image(vp), active_hollusion("buffer")))629 rev = frames[1:len(frames)-1]630 rev.reverse()631 frames.extend(rev)632 PyGif.saveAnimated(filename, frames, 1/len(frames))633 #images2gif.writeGif(filename, frames, duration=1/len(frames), dither=0, subRectangles = False)634 else:...

Full Screen

Full Screen

graphics.py

Source:graphics.py Github

copy

Full Screen

1#general tools, to port out.2#http://stackoverflow.com/questions/3204245/how-do-i-convert-a-tuple-of-tuples-to-a-one-dimensional-list-using-list-comprehe3#better learn before i go teach students4def flatten_once(ls):5 return [element for tupl in ls for element in tupl]6from tkinter import * #python 3 uses lower case for tkinter7import math8#assumption: VIEWPORT IS UNIQUE9master = Tk()10master.resizable(width=FALSE, height=FALSE)11visible = None12viewport_size = None;13image_buffer = None14img_antialias = 1 #off15try:16 from PIL import Image, ImageDraw, ImageTk # Import DNSPython17 PIL_available = True18except ImportError:19 PIL_available = False20 print("Warning: PIL was not loaded correctly")21def init(vp_size):22 global viewport_size23 viewport_size = vp_size24 master.geometry(str(viewport_size)+"x"+str(viewport_size)) #fixed window size25 return26# Graphics Auxiliary27class Posn:28 def __init__(self, x = None, y = None):29 if x is None:30 raise TypeError("Posn(x,y) - x must be a number")31 if y is None:32 raise TypeError("Posn(x,y) - y must be a number")33 self.x = x34 self.y = y35 def __add__(self, other): #huehuehue, operator overloading!36 return Posn(self.x+other.x, self.y+other.y)37 def __mul__(self, factor):38 return Posn(self.x*factor, self.y*factor)39##viewport/canvas capabilities40#a viewport is rendered bitmap buffer41def open_viewport(name, horiz, vert):42 vp, image = open_pixmap(name, horiz, vert)43 #vp.pack()44 show_viewport((vp, image))45 #vp.create_rectangle(0, 0, 600, 600, fill="white")46 return [vp, image]47#a pixmap is an unrendered pixmap buffer48 #how to do this is simple - 49 #everything below a certain screening layer is unrendered.50 #everything above is. And make sure there's only 1 thing there.51def open_pixmap(name, horiz, vert):52 #Canvas(parent, [options...])53 global viewport_size, PIL_available54 vp = Canvas(master, width=horiz, height=vert)55 image = None56 if PIL_available:57 image = Image.new("RGB", (int(horiz), int(vert)), "white") 58 vp.create_rectangle(viewport_size/6, 0, viewport_size+viewport_size/6, viewport_size, fill="white")59 vp.place(x=-(viewport_size/6))60 hide_viewport((vp, image))61 return [vp, image]62 63def show_viewport(vp):64 global visible #apparently no automatic closures.65 if vp == None:66 raise TypeError("show_viewport - vp cannot be None")67 if visible != None:68 hide_viewport(visible)69 visible = vp70 Misc.lift(vp[0], aboveThis = None)71 72def hide_viewport(vp):73 global visible #apparently no automatic closures.74 Misc.lower(vp[0], belowThis=None)75 if visible == vp and visible != None:76 visible = None77 78def clear_viewport(viewport):79 viewport[0].delete(ALL) #not nearly sure how this works.80 viewport[0].create_rectangle(viewport_size/6, 0, viewport_size+viewport_size/6, viewport_size, fill="white")81 if PIL_available:82 size = viewport[1].size #(width, height)83 viewport[1].paste("white", (0,0,size[0], size[1]))84#def copy_viewport(src, dest):85 #removed, because i can't figure out how to implement it.86 #however. i have no need to.87##color handling capabilities88##drawing capabilities89def draw_line(viewport, p1, p2, color):90 viewport[0].create_line(p1.x, p1.y, p2.x, p2.y, fill=color.hexcode())91 if PIL_available:92 draw = ImageDraw.Draw(viewport[1])93 draw.line(p1.x, p1.y, p2.x, p2.y, fill=color.hexcode())94#poly = canvas.create_polygon(x0, y0, x1, y1, ..., option, ...)95#points is a list of point objects, need to map and unpack interior twice.96def draw_solid_polygon(viewport, points, offset, color):97 points = flatten_once(map(lambda q: (q.x+offset.x, q.y+offset.y), points))98 #print(*points)99 viewport[0].create_polygon(*points, fill=color.hexcode())100 if PIL_available:101 draw = ImageDraw.Draw(viewport[1])102 draw.polygon(points, fill=color.hexcode())103 104#draw_pixels is removed, wasn't used in the JS code.105 #probably because it was used only in the 3d rendering code, and that was rewritten.106class Rgb:107 def __init__(self, r,g,b):108 self.r = round(r*255)109 self.g = round(g*255)110 self.b = round(b*255)111 def hexcode(self):112 return '#%02x%02x%02x' % (self.r, self.g, self.b)113#Import/export capabilities114#TODO: make higher quality115#Basically draws whatever is drawn to screen in parallel.116 #However, not pixel perfect.117import datetime118def saveImage(vp, filename=None):119 if PIL_available:120 if(filename == None):121 filename = datetime.datetime.now().strftime("%y%m%d-%H%M%S")122 vp[1].save(filename+".png", "PNG")123 else:124 print("PIL does not appear to be available")125def get_pixels(vp):126 if PIL_available:127 return vp[1].load()128 else:129 raise("PIL does not appear to be available")130def pixels_to_canvas(vp): 131 if len(vp) == 2: #why? because PIL doesn't keep a copy of the image, so the moment the function goes out of scope, the image DISAPPEARS.132 vp.append(ImageTk.PhotoImage(vp[1]))133 else:134 vp[2] = ImageTk.PhotoImage(vp[1])135 vp[0].create_image(0,0,image = vp[2], anchor="nw") #else it forget, and diessss136 137def get_image(vp):138 return vp[1]139 140def square(x):141 return x*x142 143def distance(p1, p2):144 return math.sqrt(square(p1.x-p2.x)+square(p1.y-p2.y))145 146def blit_pixels(viewport, inv_transform, pixels, viewport_size, image_size, mono, zmin = 0, zmax = 1):147 MAX_X = viewport_size[0]148 MAX_Y = viewport_size[1]149 IMAX_X = image_size[0]150 IMAX_Y = image_size[1]151 viewport_pix = get_pixels(viewport)152 for y in range(MAX_Y):153 for x in range(MAX_X):154 src = inv_transform(Posn(x,y)) #this is the posn on the pixels155 srcx = src.x156 srcy = src.y157 #simple 2x2 weighted sampling.158 #weight is inversely proportional to distance.159 #don't try to use this code for your homework on other modules, 160 #i haven't taken graphics and i wrote this off the top off my head.161 rsrcx = round(srcx)162 rsrcy = round(srcy)163 if(rsrcx>=0 and rsrcx<IMAX_X and rsrcy>=0 and rsrcy<IMAX_Y): #if the closest pixel is to be rendered164 #used for weighing165 dsrcx = srcx - rsrcx #+ve => right166 dsrcy = srcy - rsrcy #+ve => up167 #used to figure out which pixel we are actually weighing against.168 if(dsrcx>=0):169 esrcx = 1170 else:171 esrcx = -1172 if(dsrcy>=0):173 esrcy = 1174 else:175 esrcy = -1176 original = Posn(srcx, srcy)177 dtgt = 1/(distance(Posn(rsrcx, rsrcy),original)+0.01)178 dtgtdx = 1/(distance(Posn(rsrcx+esrcx, rsrcy),original)+0.01)179 dtgtdy = 1/(distance(Posn(rsrcx, rsrcy+esrcy),original)+0.01)180 dtgtdxdy = 1/(distance(Posn(rsrcx+esrcx, rsrcy+esrcy),original)+0.01)181 tgt = pixels[rsrcx, rsrcy]182 #try to get pixel colour values if possible183 #if not possible, disable the weight184 if(rsrcx+esrcx>= 0 and rsrcx+esrcx<IMAX_X):185 tgtdx = pixels[rsrcx+esrcx, rsrcy]186 else:187 dtgtdx = 0188 dtgtdxdy = 0189 tgtdx = (0,0,0)190 if(rsrcy+esrcy>= 0 and rsrcy+esrcy<IMAX_Y):191 tgtdy = pixels[rsrcx, rsrcy+esrcy]192 else:193 dtgtdy = 0194 dtgtdxdy = 0195 tgtdy = (0,0,0)196 if(dtgtdxdy!=0):197 tgtdxdy = pixels[rsrcx+esrcx, rsrcy+esrcy]198 else:199 tgtdxdy = (0,0,0)200 divisor = (dtgt + dtgtdx + dtgtdy + dtgtdxdy)201 tcolor = (round((dtgt*tgt[0]+dtgtdx*tgtdx[0]+dtgtdy*tgtdy[0]+dtgtdxdy*tgtdxdy[0])/divisor),\202 round((dtgt*tgt[1]+dtgtdx*tgtdx[1]+dtgtdy*tgtdy[1]+dtgtdxdy*tgtdxdy[1])/divisor), \203 round((dtgt*tgt[2]+dtgtdx*tgtdx[2]+dtgtdy*tgtdy[2]+dtgtdxdy*tgtdxdy[2])/divisor))204 def rescale(color):205 if color>=254:206 return 255207 else:208 return round(zmin*255 + (zmax-zmin)*color)209 tcolor = (rescale(tcolor[0]), rescale(tcolor[1]), rescale(tcolor[2]))210 viewport_pix[x,y] = (min(tcolor[0], viewport_pix[x,y][0]), min(tcolor[1], viewport_pix[x,y][1]), min(tcolor[2], viewport_pix[x,y][2]))211 pixels_to_canvas(viewport)212 213#TODO: test how it renders out of range pixels 214 #no one should up-sample with this algorithm -.-215# def blit_pixels(viewport, transform, pixels, viewport_size, image_size, mono):216 # global img_antialias217 # MAX_X = image_size[0]218 # MAX_Y = image_size[1]219 # tviewport = open_pixmap("temp", viewport_size[0]*img_antialias, viewport_size[1]*img_antialias)220 # bound_x = img_antialias*viewport_size[0]221 # bound_y = img_antialias*viewport_size[1]222 # target_pix = get_pixels(tviewport)223 # for y in range(MAX_Y):224 # for x in range(MAX_X):225 # p = Posn(x,y)226 # transposn = transform(p)227 # t_x = transposn.x228 # t_y = transposn.y229 # if(t_x>=0 and t_x<=bound_x and t_y>=0 and t_y<=bound_y):230 # if mono:231 # colour = pixels[x,y]232 # avg = round(colour[0]+colour[1]+colour[2]/3)233 # target_pix[t_x, t_y] = (avg, avg, avg)234 # else:235 # target_pix[t_x, t_y] = pixels[x,y]236 # vp_size = get_image_size(viewport)237 # MAX_X = vp_size[0]238 # MAX_Y = vp_size[1]239 ##will leave some dots at the edge.240 ##but MUAHAHAHAHAHHAHAHAHAHAHAHAHAHAHAHAH241 ##DOES NOT CARE242 # white = (255,255,255)243 # for y in range(1,MAX_Y-1):244 # for x in range(1,MAX_X-1):245 # if(target_pix[x,y]== white):246 # up = target_pix[x,y-1]247 # down = target_pix[x,y+1]248 # left = target_pix[x-1, y]249 # right = target_pix[x+1, y]250 # ul = target_pix[x-1, y+1]251 # ur = target_pix[x+1, y+1]252 # dl = target_pix[x-1, y-1]253 # dr = target_pix[x-1, y-1]254 # if(up == white and down == white and left == white and right == white):255 # colour_r = (ul[0]+ur[0]+dl[0]+dr[0])/4256 # colour_g = (ul[1]+ur[1]+dl[1]+dr[1])/4257 # colour_b = (ul[2]+ur[2]+dl[2]+dr[2])/4258 # target_pix[x,y] = (round(colour_r), round(colour_g), round(colour_b))259 # else:260 # colour_r = (ul[0]+ur[0]+dl[0]+dr[0]+up[0]+down[0]+left[0]+right[0])/8261 # colour_g = (ul[1]+ur[1]+dl[1]+dr[1]+up[1]+down[1]+left[1]+right[1])/8262 # colour_b = (ul[2]+ur[2]+dl[2]+dr[2]+up[2]+down[2]+left[2]+right[2])/8263 # target_pix[x,y] = (round(colour_r), round(colour_g), round(colour_b))264 ##TODO: enhancement, averaging for points which have been missed out265 # viewport[1] = tviewport[1].resize((viewport_size[0], viewport_size[1]), Image.ANTIALIAS)266 # pixels_to_canvas(viewport)267 268def get_image_size(img):269 return img[1].size270def load_image(filename): #returns a vp271 global img_antialias272 if PIL_available:273 img = Image.open(filename)274 img = img.convert('RGB')275 width, height = img.size276 img = img.resize((img_antialias*width, img_antialias*height), Image.BICUBIC)277 tkcanvas, pilcanvas = open_pixmap(filename, img_antialias*width, img_antialias*height)278 return (tkcanvas, img)279 else:...

Full Screen

Full Screen

screenshot.py

Source:screenshot.py Github

copy

Full Screen

1from cefpython3 import cefpython as cef2import os3import platform4import subprocess5import sys6try:7 from PIL import Image8except ImportError:9 print("PIL is not installed,")10 "Install using: pip install PIL"11 sys.exit(1)12import tkinter as tk13VIEWPORT_SIZE = None14URL = None15SCREENSHOT_PATH = None16def main(url, w, h):17 global VIEWPORT_SIZE, URL, SCREENSHOT_PATH18 URL = url19 VIEWPORT_SIZE = (w, h)20 SCREENSHOT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)),21 "SCREENSHOT.png") # current working dir22 check_versions()23 sys.excepthook = cef.ExceptHook # to shutdown all the processes while errors24 if os.path.exists(SCREENSHOT_PATH):25 print("Remove old screenshot")26 os.remove(SCREENSHOT_PATH)27 command_line_arguments()28 settings = {29 "windowless_rendering_enabled": True,30 }31 switches = {32 "disabled-gpu": "",33 "disabled-gpu-compositing": "",34 "enable-begin-frame-scheduling": "",35 "disable-surfaces": ""36 }37 browser_settings = {38 "windowless_frame_rate": 30,39 }40 cef.Initialize(settings=settings, switches=switches)41 create_browser(browser_settings)42 cef.MessageLoop()43 cef.Shutdown()44 print("Opening your screenshot with the default application")45 open_with_default_application(SCREENSHOT_PATH)46def check_versions():47 ver = cef.GetVersion()48 print("CEF Python {ver}".format(ver=ver['version']))49 print("Chromium {ver}".format(ver=ver['chrome_version']))50 print("CEF {ver}".format(ver=ver['cef_version']))51 print("Python {ver} {arch}".format(ver=platform.python_version(),52 arch=platform.architecture()[0]))53 assert cef.__version__ >= '57.0', "CEF Python v57.0+ required to run this"54def command_line_arguments():55 if len(sys.argv) == 4:56 url = sys.argv[1]57 width = int(sys.argv[2])58 height = int(sys.argv[3])59 if url.startswith("http://") or url.startswith("https://"):60 global URL61 URL = url62 else:63 print("Error: Invalid URL entered")64 sys.exit(1)65 if width > 0 and height > 0:66 global VIEWPORT_SIZE67 VIEWPORT_SIZE = (width, height)68 else:69 print("Error: Invalid Width and/or Height")70 sys.exit(1)71 elif len(sys.argv) > 1:72 print("Error: Expected arguments not received")73 sys.exit(1)74def create_browser(settings):75 global VIEWPORT_SIZE, URL76 parent_window_handle = 077 window_info = cef.WindowInfo()78 window_info.SetAsOffscreen(parent_window_handle)79 print("Viewport size: {size}".format(size=str(VIEWPORT_SIZE)))80 print("Loading URL: {url}".format(url=URL))81 browser = cef.CreateBrowserSync(window_info=window_info, settings=settings, url=URL)82 browser.SetClientHandler(LoadHandler())83 browser.SetClientHandler(RenderHandler())84 browser.SendFocusEvent(True)85 browser.WasResized()86def save_screenshot(browser):87 global SCREENSHOT_PATH88 buffer_string = browser.GetUserData("OnPaint.buffer string")89 if not buffer_string:90 raise Exception("buffer_string is empty because"91 " OnPaint never called?")92 image = Image.frombytes("RGBA", VIEWPORT_SIZE, buffer_string, "raw", "RGBA", 0, 1)93 image.save(SCREENSHOT_PATH, "PNG")94 print("Saved screenshot to: {path}".format(path=SCREENSHOT_PATH))95def open_with_default_application(path):96 if sys.platform.startswith("darwin"): # Mac operating system97 subprocess.call(("open", path))98 elif os.name == "nt":99 os.startfile(path)100 elif os.name == '"posix':101 subprocess.call(("xdg-open", path))102def exit_app(browser):103 print("Closing Browser and Exiting Application")104 browser.CloseBrowser()105 cef.QuitMessageLoop()106class LoadHandler(object):107 def OnLoadingStateChange(self, browser, is_loading, **_):108 if not is_loading:109 sys.stdout.write(os.linesep)110 print("Website has been loaded")111 save_screenshot(browser)112 cef.PostTask(cef.TID_UI, exit_app, browser)113 def OnLoadError(self, browser, frame, error_code, failed_url, **_):114 if not frame.IsMain():115 return116 print("Failed to load URL: {url}".format(url=failed_url))117 print("Error code: {code}".format(code=error_code))118 cef.PostTask(cef.TID_UI, exit_app, browser)119class RenderHandler(object):120 def __init__(self):121 self.OnPaint_called = False122 def GetViewRect(self, rect_out, **_):123 rect_out.extend([0, 0, VIEWPORT_SIZE[0], VIEWPORT_SIZE[1]])124 return True125 def OnPaint(self, browser, element_type, paint_buffer, **_):126 if self.OnPaint_called:127 sys.stdout.write(".")128 sys.stdout.flush()129 else:130 sys.stdout.write("OnPaint")131 self.OnPaint_called = True132 if element_type == cef.PET_VIEW:133 buffer_string = paint_buffer.GetBytes(mode='rgba', origin='top-left')134 browser.SetUserData("OnPaint.buffer string", buffer_string)135 else:136 raise Exception("Unsupported element type in OnPaint")137root = tk.Tk()138root.geometry("400x200")139class Widgets:140 def __init__(self, label_text, default_value):141 self.lab = tk.Label(root, text=label_text)142 self.lab.pack()143 self.v = tk.StringVar()144 self.entry = tk.Entry(root, textvariable=self.v)145 self.entry.pack()146 self.v.set(default_value)147obj1 = Widgets("Enter Website Name: ", "https://www.google.com")148obj2 = Widgets("Enter Width: ", "1024")149obj3 = Widgets("Enter Height: ", "2048")150root.bind("<Return>", lambda x: main(obj1.v.get(), int(obj2.v.get()), int(obj3.v.get())))151label4 = tk.Label(root, text=" ")152label4.pack()153label5 = tk.Label(root, text="Press the Enter key to create screenshot")154label5.pack()...

Full Screen

Full Screen

render.py

Source:render.py Github

copy

Full Screen

1from glumpy import app, gloo, gl2from contextlib import contextmanager3import numpy as np4try:5 import pycuda.driver6 from pycuda.gl import graphics_map_flags, BufferObject7 _PYCUDA = True8except ImportError as err:9 print('pycuda import error:', err)10 _PYCUDA = False11import torch12class OffscreenRender:13 def __init__(self, viewport_size, out_buffer_location='opengl', clear_color=None):14 self._init_buffers(viewport_size, out_buffer_location)15 self.clear_color = clear_color if clear_color is not None else (0., 0., 0., 1.)16 def _init_buffers(self, viewport_size, out_buffer_location):17 assert out_buffer_location in ['torch', 'opengl', 'numpy']18 if out_buffer_location == 'torch':19 assert _PYCUDA, 'pycuda is not available'20 try:21 import pycuda.gl.autoinit # this may fails in headless mode22 except:23 raise RuntimeError('PyCUDA init failed, cannot use torch buffer')24 _ = torch.cuda.FloatTensor(1, 3, 512,512) # needs init here, otherwise does not work25 color_np = np.zeros((viewport_size[1], viewport_size[0], 4), np.float32)26 self.color_buf, self.color_buf_cuda = create_shared_texture(color_np)27 self.out_buf = torch.zeros((viewport_size[1], viewport_size[0], 4), dtype=torch.float32).cuda()28 elif out_buffer_location == 'opengl':29 self.color_buf = np.zeros((viewport_size[1], viewport_size[0], 4), dtype=np.float32).view(gloo.TextureFloat2D)30 self.out_buf = self.color_buf31 elif out_buffer_location == 'numpy':32 self.color_buf = np.zeros((viewport_size[1], viewport_size[0], 4), dtype=np.float32).view(gloo.TextureFloat2D)33 self.out_buf = np.zeros((viewport_size[1], viewport_size[0], 3), dtype=np.float32)34 self.viewport_size = viewport_size35 self.out_buffer_location = out_buffer_location36 self.depth_buf = gloo.DepthBuffer(viewport_size[0], viewport_size[1], gl.GL_DEPTH_COMPONENT32)37 self.fbo = gloo.FrameBuffer(color=self.color_buf, depth=self.depth_buf)38 def render(self, scene, cull_face=True):39 self.fbo.activate()40 gl.glEnable(gl.GL_PROGRAM_POINT_SIZE)41 gl.glEnable(gl.GL_DEPTH_TEST)42 gl.glShadeModel(gl.GL_FLAT)43 if cull_face:44 gl.glEnable(gl.GL_CULL_FACE)45 gl.glCullFace(gl.GL_BACK)46 else:47 gl.glDisable(gl.GL_CULL_FACE)48 49 gl.glClearColor(*self.clear_color)50 gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)51 gl.glViewport(0, 0, self.viewport_size[0], self.viewport_size[1])52 if scene.draw_points:53 scene.program.draw(gl.GL_POINTS)54 else:55 assert scene.index_buffer is not None56 scene.program.draw(gl.GL_TRIANGLES, scene.index_buffer)57 if self.out_buffer_location == 'torch':58 frame = cpy_texture_to_tensor(self.color_buf_cuda, self.out_buf).clone()59 elif self.out_buffer_location == 'opengl':60 frame = self.out_buf61 else:62 gl.glReadPixels(0, 0, self.viewport_size[0], self.viewport_size[1], gl.GL_RGB, gl.GL_FLOAT, self.out_buf)63 frame = self.out_buf.copy()64 self.fbo.deactivate()65 return frame66@contextmanager67def cuda_activate_array(img):68 """Context manager simplifying use of pycuda.gl.RegisteredImage"""69 mapping = img.map()70 yield mapping.array(0,0)71 mapping.unmap()72@contextmanager73def cuda_activate_buffer(buf):74 mapping = buf.map()75 yield mapping.device_ptr()76 mapping.unmap()77def create_shared_texture(arr, map_flags=None):78 """Create and return a Texture2D with gloo and pycuda views."""79 if map_flags is None:80 map_flags = graphics_map_flags.WRITE_DISCARD81 82 gl_view = arr.view(gloo.TextureFloat2D)83 gl_view.activate() # force gloo to create on GPU84 gl_view.deactivate()85 cuda_view = pycuda.gl.RegisteredImage(86 int(gl_view.handle), gl_view.target, map_flags)87 return gl_view, cuda_view88def create_shared_buffer(arr):89 """Create and return a BufferObject with gloo and pycuda views."""90 gl_view = arr.view(gloo.VertexBuffer)91 gl_view.activate() # force gloo to create on GPU92 gl_view.deactivate()93 cuda_view = BufferObject(np.long(gl_view.handle))94 return gl_view, cuda_view95def cpy_texture_to_tensor(texture, tensor):96 """Copy GL texture (cuda view) to pytorch tensor"""97 with cuda_activate_array(texture) as src:98 cpy = pycuda.driver.Memcpy2D()99 cpy.set_src_array(src)100 cpy.set_dst_device(tensor.data_ptr())101 cpy.width_in_bytes = cpy.src_pitch = cpy.dst_pitch = tensor.shape[1] * 4 * 4 102 cpy.height = tensor.shape[0] 103 cpy(aligned=False)104 torch.cuda.synchronize()105 return tensor106def cpy_tensor_to_texture(tensor, texture):107 """Copy pytorch tensor to GL texture (cuda view)"""108 with cuda_activate_array(texture) as ary:109 cpy = pycuda.driver.Memcpy2D()110 cpy.set_src_device(tensor.data_ptr())111 cpy.set_dst_array(ary)112 cpy.width_in_bytes = cpy.src_pitch = cpy.dst_pitch = tensor.shape[1] * 4 * 4 113 cpy.height = tensor.shape[0] 114 cpy(aligned=False)115 torch.cuda.synchronize()116 return tensor117def cpy_buffer_to_tensor(buffer, tensor):118 """Copy GL buffer (cuda view) to pytorch tensor"""119 n = tensor.numel()*tensor.element_size() 120 with cuda_activate_buffer(buffer) as buf_ptr:121 pycuda.driver.memcpy_dtod(tensor.data_ptr(), buf_ptr, n)122def cpy_tensor_to_buffer(tensor, buffer):123 """Copy pytorch tensor to GL buffer (cuda view)"""124 n = tensor.numel()*tensor.element_size() 125 with cuda_activate_buffer(buffer) as buf_ptr:...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful