Repository navigation
feat(html5): add the experimental view_set_viewport (non-rectangular viewports) - #806
Conversation
…viewports) HTML5 version of the C++ runner's view_set_viewport (GMS2-Runner-Main#1076, GMS2-Runner-Main#1082). It takes an array of viewport structs, one per view from 0, or a JSON string of one. Each struct can set polygons (x,y pairs in the view surface's pixels; [] turns the polygon off), the port (screenX/Y/W/H), the room rectangle (roomRectX/Y/W/H, also applied to the view's camera) and startFunc/endFunc callbacks. - view_set_viewport (Function_Graphics.js) ear clips each polygon into a triangle list kept on the room's yyView, and writes the port, room rectangle, visibility and surface into the view arrays. A view without a surface gets one of screenW x screenH. - DrawViews draws a polygon view's surface through its triangles at the view's port position once the surface is no longer the target: onto the application surface, or the canvas without one. Port units are scaled by the display scale, as for the rectangular views. WebGL fills a triangle list from the surface's texture; Canvas clips to the triangles and draws the surface image. startFunc and endFunc run around the triangles. - The mouse-to-view lookup hit tests a polygon view's triangles. - Leaving a non-persistent room frees the surfaces view_set_viewport created for its views. - Everything is behind @if function("view_set_viewport"), and the WebGL path uses AllocVerts directly, so it doesn't need the primitive builder to be in the build.
iampremo
left a comment
There was a problem hiding this comment.
Reviewed at 77f59d4.
The drawing, mouse hit testing and ear clipping look right to me. The WebGL path follows the existing AllocVerts quad code, and the canvas clip works because every ear-clipped triangle has the same winding.
There's one real problem. When you call view_set_viewport a second time to update a polygon, the surface it created on the first call gets freed. A new one is only made if screenW/screenH are passed again. So a polygon-only update leaves the view drawing as a plain rectangle, and nothing reports an error. Details are inline. There's also a question about rooms where views aren't enabled.
Automated reviewThis PR adds the experimental The fixes for the earlier review are in place:
One new problem remains: the runner-created surface leaks when a persistent room is rebuilt by Open: 1 issue. New in this review: the review comments. Reviewed 89315d3 Advisory: this check doesn't block merging. It runs again on each push. Reply in a comment's thread if it is wrong, and resolve the thread once it is dealt with: the next review reads both. |
…era, hit-tests in every mouse path - A call that gives a polygon keeps the surface view_set_viewport made while it is the port's size (the port's size is the fallback when screenW/screenH are left out), and only remakes it when the size changes. A surface the game set is used and never freed; ours is only freed while it is still the view's surface. - Every field, startFunc/endFunc included, is applied only when it is given. polygons : [] turns the polygon off, frees our surface and clears the callbacks. screenW/H and roomRectW/H must be > 0. - The room rectangle rebuilds the camera's matrices, as the camera_set_view_* functions do. - DrawPolygon runs the callbacks it started with and looks the polygon and surface up again after startFunc, so startFunc can call view_set_viewport or free the surface. - The mouse uses the polygon only when it is drawn, and the rectangle test no longer sits in an @else (raw, unpreprocessed scripts ran both). window_views_mouse_get_x/y, GR_Window_Views_Convert and the touch path now skip a polygon view when the point is outside its triangles. Claude-Session: https://claude.ai/code/session_01EgTASfpMoBvX7TBDy119t5
… own As in the C++ runner (GMS2-Runner-Main#1082): when the game replaces the view's surface (view_set_surface_id, view_surface_id = , or view_surface_id[n] = , picked up when the arrays are copied into the views), the surface view_set_viewport made is freed and forgotten instead of leaking. The game's surface is never freed. Claude-Session: https://claude.ai/code/session_01EgTASfpMoBvX7TBDy119t5
iampremo
left a comment
There was a problem hiding this comment.
Reviewed at 7bb05ba.
Re-reviewed at 7bb05ba. Both of my earlier points are dealt with.
- Polygon-only update: fixed. On a call that passes
polygons,EnsurePolygonSurfacefirst runsCheckPolygonSurface, which keeps our surface whileview_surface_id[index]still points to it. It then reuses the surface if it matchesview_wport/view_hportand only recreates it when the size changes. So a later{ polygons: [...] }call keeps S, and updating the polygon every step no longer frees and recreates the surface. A first call with onlypolygonsnow gets a surface the size of the port. A surface the game set itself is left alone and never freed.CheckPolygonSurfacealso runs fromview_set_surface_id, theview_surface_idsetter andCopyViewsFromArrays, so ours is freed once the game replaces it. - Views not enabled: the answer holds. The doc comment on
view_set_viewportnow says it works likeview_set_visibleand doesn't turn views on. I'm fine with that matching the C++ runner, so I won't ask again.
I also checked the bot's four findings at HEAD, and all are fixed:
- The camera matrices are rebuilt with
Build2DView/Build3DView, the same pattern ascamera_create_view. - The
@elsemouse branches are gone, andIO_StartStepnow setsinViewfrom the polygon test. - The polygon-only update is the fix above.
DrawPolygonlooks up the polygon and surface again afterstartFunc. IfstartFuncfrees the surface or turns the polygon off, the draw is skipped and nothing touches a freed surface. If it resizes the port, the new surface is drawn, and nothing has been queued against the old texture by then.
The hit-test maths checks out. ContainsCanvasPoint turns a canvas position back into port units with scaledportw/portw, which undoes the portx * sx * asx + g_AppSurfaceRect.x mapping in DrawViews. So the mouse test and the drawn triangles line up. Looks good to me.
…rame; error on polygons that can't be clipped - Before a view with a polygon is drawn, the surface view_set_viewport made is made again if it has been lost (it no longer exists) or the port's size has changed (view_wport[n] =, view_set_wport). A surface the game set isn't touched. A lost surface stays ours until the game replaces it, so it can be remade. - The ear clip stops once a full pass over the remaining vertices finds no ear, and view_set_viewport raises "polygon N couldn't be triangulated, is it self-intersecting?", as the C++ runner and GMRT do, instead of running to a guard. Claude-Session: https://claude.ai/code/session_01EgTASfpMoBvX7TBDy119t5
…he C++ runner does A vertex on a straight line between its neighbours is dropped without a triangle, and a degenerate last triangle is skipped, matching GMS2-Runner-Main#1082 (0fd2439ad). A polygon with no area (all points on a line) now turns the polygon off, as in C++, instead of being drawn as a zero-area triangle. Claude-Session: https://claude.ai/code/session_01EgTASfpMoBvX7TBDy119t5
…or have no area After clipping, the triangles' total area is compared with the polygon's (shoelace) area, with GMRT's tolerance (1e-3 of the area, at least 1). A polygon that crosses itself (a bow tie, a star) can still find ears, but its triangles then overlap or spill outside it and the areas differ. 3 or more points that give no triangle (all on one line) are rejected too. Both raise "view_set_viewport(): polygon N couldn't be split into triangles; it may cross itself, or have all its points on one line", as GMRT#7256 (46b4ea0729) and GMS2-Runner-Main#1082 do. Claude-Session: https://claude.ai/code/session_01EgTASfpMoBvX7TBDy119t5
The point-in-triangle test was strict, so a reflex corner lying exactly on the ear's edge didn't block it, and a valid polygon such as [0,0, 10,0, 10,10, 5,5, 0,10] was clipped across its notch and rejected. Points on the boundary now block the ear, except one on the triangle's own corners (a duplicate vertex). Found in review of GMRT#7256. Claude-Session: https://claude.ai/code/session_01EgTASfpMoBvX7TBDy119t5
… startFunc/endFunc startFunc and endFunc are resolved like getFunction does for the array functions: a JS function (a method, or a script function) is used as it is, and a script index (how a script function reaches the runner in these builds) is looked up in JSON_game.Scripts. undefined clears the callback, and anything else raises an error naming the field. They're resolved before any of the entry is applied. A method runs on the struct or instance it's bound to, a script function on global. Before this, a script function given as endFunc was silently ignored. Claude-Session: https://claude.ai/code/session_01EgTASfpMoBvX7TBDy119t5
…hat reuses its ID Surface IDs are reused as soon as they're freed, so after the game frees the view's surface the next surface_create anywhere gets the same ID. The runner now keeps the surface object it created as well as the ID, and treats the surface as its own only while that ID still holds that object. Otherwise the ID is forgotten without being freed: - the per-frame check makes the view a new surface, leaving the game's alone; - when the game sets the view's surface (view_set_surface_id, view_surface_id =) to a surface that reused the ID, it is the game's, so it is used and never freed. Claude-Session: https://claude.ai/code/session_01EgTASfpMoBvX7TBDy119t5
iampremo
left a comment
There was a problem hiding this comment.
Reviewed at 89315d3.
Re-reviewed at 89315d3, looking at what changed since 7bb05ba.
Both points from my last review still hold. A polygon-only update keeps the surface, a surface the game set is never freed, and the doc comment still says the function doesn't turn views on. The new per-frame RefreshPolygonSurface in DrawViews matches the description. It remakes our surface when it's lost or the port size changes, and doesn't touch a surface the game set.
Both of the bot's open findings are fixed:
startFunc/endFuncnow accept a method or a script index (≥100000, resolved throughJSON_game.Scriptsas inyyVariable.js), and anything else raises an error. A method now runs on itsboundObject.- The ID-reuse problem is handled by keeping the surface object as well as the ID. I went through the reuse cases: the game frees ours and creates its own with the same ID, with or without
view_set_surface_id. Both leave the game's surface alone.
The ear clip changes look right to me. The miss counter ends the loop, turn == 0 drops points that lie on a line, an edge point blocks an ear, and the area check catches bow ties and all-points-on-one-line input.
One regression came in with the object-identity check, so I'm asking for changes. surface_resize puts a new object under the same ID, so the runner stops seeing a resized surface as its own and never frees it. Details are inline.
…e resizes it surface_resize puts a new object under the same surface ID (surface_create with _forceid), so the object-identity check from 89315d3 treated a resized surface as not ours: the per-frame check forgot it without freeing it and made a new one, leaking a surface per frame for a game that kept resizing its view surface. Our surface object is now tagged with the view that made it (m_viewPolygonOwner), both _forceid paths in surface_create (Canvas and WebGL) carry the tag over to the replacement, and ownership checks the tag. A surface that merely reused a freed ID has no tag, so the ID-reuse protection stays. Claude-Session: https://claude.ai/code/session_01EgTASfpMoBvX7TBDy119t5
iampremo
left a comment
There was a problem hiding this comment.
Reviewed at 1084c17.
Re-reviewed at 1084c17, looking at what changed since 89315d3.
The surface_resize regression I raised is fixed, and the reply matches the code. EnsurePolygonSurface tags the object it makes with m_viewPolygonOwner = this. Both _forceid paths in surface_create copy the tag onto the replacement object before g_Surfaces.Set: Canvas copies it to pSurf (Function_Surface.js:174-175) and WebGL to pTPE (yyWebGL.js:3880-3881). Each sits inside @if function("view_set_viewport"). In both modes that's the object that ends up under the ID, so OwnsPolygonSurface stays true after a resize. The next RefreshPolygonSurface then frees the resized surface and makes a port-sized one, instead of orphaning it. Only surface_create replaces a surface under the same ID, and only surface_resize reaches it, after its surface_exists check. So no other replacement path needs the tag.
The ID-reuse protection still holds. A surface the game creates after freeing ours is a new object with no tag, so OwnsPolygonSurface is false and the ID is forgotten without being freed. A same-ID surface set through view_set_surface_id goes through CheckPolygonSurface(_, true) and is left alone, as before.
The other points from my earlier reviews haven't changed since 89315d3:
- A polygon-only update keeps the surface.
- A surface the game set is never freed.
- The doc comment still says the function doesn't turn views on.
Neither of the bot's findings is still open. startFunc/endFunc accept a method or a script index and reject anything else (39aefa3). Tracking the surface by ID alone is replaced by the owner tag.
Looks good to me.
| // @if function("view_set_viewport") | ||
| // free the surfaces view_set_viewport created for the room's views | ||
| for (var v = 0; v < g_RunRoom.m_Views.length; v++) { | ||
| if (g_RunRoom.m_Views[v]) g_RunRoom.m_Views[v].ResetPolygon(v); |
There was a problem hiding this comment.
The surface view_set_viewport made is only freed here, when leaving a non-persistent room. game_restart from a persistent room skips this block.
What happens:
game_restartsetsROOM_RESTARTGAME, which runsRun_EndGame→ResetAll→StartGame→StartRoom(startRoom, true).- Because
g_RunRoom.m_persistentis true,ResetPolygonnever runs. _startingthen forcesispersistent = false, soCreateRoomFromStoragecallsInit(), which doesm_Views = [].- The old
yyView, and the only record ofm_polygonSurface, are dropped. The surface stays allocated ing_Surfaces(a WebGL framebuffer and texture) and nothing can free it anymore.
Result: each restart leaks one surface per polygon view.
Fix: free the polygons wherever a room's views get replaced, not only on this path. For example, at the top of yyRoom.prototype.CreateRoomFromStorage (before this.Init()), run ResetPolygon(v) on each existing this.m_Views[v], inside the same @if function("view_set_viewport") block. Another option is to also run this loop when _starting is true.
Adds the experimental
view_set_viewportto the HTML5 runner: non-rectangular viewports, https://github.com/YoYoGames/GMS2-Runner-Main/issues/1076. The other sides are the C++ runner YoYoGames/GMS2-Runner-Main#1082, the asset compiler YoYoGames/GameMaker#5452 and GMRT YoYoGames/GMRT#7256.view_set_viewport(viewportData)takes an array of structs, one per view starting at view 0 (at most 8), or a JSON string of one. Each struct can set:polygons:[x0, y0, x1, y1, ...], a simple polygon (concave is fine) in the view surface's pixels. A polygon that can't be split into triangles raises "view_set_viewport(): polygon N couldn't be split into triangles; it may cross itself, or have all its points on one line", as in the C++ runner and GMRT. That covers a polygon that crosses itself, and 3 or more points that all lie on one line. The ear clip matches the other runners':[]turns the polygon off, frees the surfaceview_set_viewportmade, and clears the callbacks;screenX,screenY,screenW,screenH;roomRectX,roomRectY,roomRectW,roomRectH, which also moves the view's camera;startFuncandendFunc, called before and after the polygon is drawn (to set and reset a shader, for example).undefinedclears it, and anything else raises an error naming the field.global.Only the fields that are given change; everything left out keeps its value, callbacks included.
screenW,screenH,roomRectWandroomRectHmust be greater than 0. As withview_set_visible, the room needs views enabled; the function doesn't turn them on.How it works:
view_set_viewport(Function_Graphics.js) ear clips each polygon into a triangle list kept on the room'syyView. It writes the port, room rectangle, visibility and surface into theg_pBuiltInview arrays, whichUpdateViewscopies into the views each frame. When a room rectangle is given, it rebuilds the camera's matrices, ascamera_set_view_*do.view_set_viewportmakes one the port's size. It is kept while it stays that size, so updating the polygon every step reuses it, and made again only when the size changes.view_wport[n] =,view_set_wport). The HTML5 runner doesn't handle WebGL context loss itself, so "lost" here means the surface no longer exists.polygons : []or by leaving a non-persistent room, and only while it is still the view's surface.view_set_surface_id,view_surface_id[n] =), ours is freed and forgotten, as in the C++ runner. The game's surface is never freed.m_viewPolygonOwner). The surface is ours only while the object under that ID carries the tag; otherwise the ID is forgotten without being freed, and the view gets a new surface. A surface the game set that reused the ID is the game's.surface_resizereplaces the object under the same ID (surface_createwith_forceid). Both of those paths, Canvas and WebGL, copy the tag over, so a surface the game resizes is still ours: it is put back to the port's size and freed as usual.DrawViews, once a polygon view has been drawn into its surface and that surface is no longer the target, the surface is drawn through the triangles at the view's current port position. It goes onto the application surface, or onto the canvas when there isn't one. Port units are scaled by the display scale, as for the rectangular views.AllocVerts.startFuncandendFuncrun around the triangles. The polygon and surface are looked up again afterstartFunc, so it can callview_set_viewportor free the surface.window_views_mouse_get_x/y(GML'smouse_x/mouse_y),GR_Window_Views_Convert, the internal lookup inyyIOManager.jsand the touch path all skip a polygon view when the point is outside its triangles. A view with a polygon but no surface is drawn and hit-tested as a rectangle.@if function("view_set_viewport"). The WebGL path doesn't use thedraw_primitive_*builder, so it still works in a build that strips the builder out.As in GMRT, the polygon follows the view's current port position.
Tests (headless Chrome, Igor 2026.0.0.23, a GMAssetCompiler with #5452). YoYoGames/GM-TestFramework#386's
BasicViewSetViewportTestSuite:scripts/; at 39aefa3 also stripped (5 tests: "keeps its surface the port's size" Passed (5); the first test'sendFuncis a script function; Errors also expects a non-functionstartFuncto throw, and accepts the notch square and a square at (30000.3, 20000.7))endFuncwas never called)startFunc)scripts/(5 tests: also "keeps its surface the port's size", Passed (5); Errors also expects a polygon with no ear and a bow tie to throw)scripts/(5 tests, "keeps its surface the port's size" Passed (5))scripts/scripts/scripts/, at fdc06e4 (per-frame surface check, triangulation error)scripts/, after the surface-replacement fixStripped builds: "obfuscated + conditional compilation" means the
HTML5.obfuscateandHTML5.confitional_compilationsettings were on. ViewportTriangles with itsview_set_viewportcalls taken out builds without any of this code: the error strings are gone and the file is 7.6 KB smaller. It runs with no errors.The issue's ViewportTriangles project, WebGL and Canvas (it calls
view_set_viewportwith all its data every step):startFunc/endFuncrun once per view per frame (about 600 frames in 10 s), with no errors. It also ran clean as a stripped build.mouse_xin the right view, scrolled room included.Surface and triangulation checks (CDP, the ViewportTriangles project, WebGL and Canvas):
surface_freeon the auto surface: remade by the next frame.view_set_wport/view_set_hportto 640x480: the surface was remade at 640x480.view_set_surface_idand aview_set_wportchange: the game's surface was left at its own size.view_set_surface_id: the game's surface is used, andpolygons: []leaves it alive.surface_resizeof the view's surface (121 frames):polygons: []frees it.Not run on a phone.