can you optimise my line drawing..…
- User
can you optimise my line drawing..
-- OSGL v1.4b - Open-Source-Graphical-Library -- Copyright © 2023-2024 Gunshot Sound Studios (@saaawdust)
-- This software is provided ‘as-is’, without any express or implied warranty. -- In no event will the authors be held liable for any damages arising from the use of this software.
-- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it freely, -- subject to the following restrictions:
-- 1. The origin of this software must not be misrepresented; -- you must not claim that you wrote the original software. -- If you use this software in a product, an acknowledgment -- in the product documentation would be appreciated but is not required.
-- 2. Altered source versions must be plainly marked as such, -- and must not be misrepresented as being the original software.
-- 3. This notice may not be removed or altered from any source distribution.
local OSGL = script.Parent.Parent local draw = OSGL.draw local pixel = require(draw.pixel)
local types = require(OSGL.types)
return function(object: types.DrawableObject, startX: number, startY: number, stopX: number, stopY: number, thickness: number, color: types.Color) thickness = thickness or 1 color = color or color.BLACK
local sizeX, sizeY = object.sizeX, object.sizeY local dx = stopX - startX local dy = stopY - startY local steps = math.max(math.abs(dx), math.abs(dy)) local xIncrement = dx / steps local yIncrement = dy / steps local x = startX local y = startY local function drawThickPoint(px: number, py: number, thickness: number) local halfThickness = thickness / 2 for offsetX = -halfThickness, halfThickness do for offsetY = -halfThickness, halfThickness do local pixelX = math.floor(px + offsetX + 0.5) local pixelY = math.floor(py + offsetY + 0.5) if pixelX >= 0 and pixelX < sizeX and pixelY >= 0 and pixelY < sizeY then pixel(object, pixelX, pixelY, color) end end end end for _ = 0, steps do drawThickPoint(x, y, thickness) x += xIncrement y += yIncrement endend
- Assistant
Your line drawing function appears to be efficient in its basic structure, but there are a few optimizations and improvements we can make to ensure better performance and potentially cleaner code. Here are some modifications you might consider implementing:
Optimized Line Drawing Function
local OSGL = script.Parent.Parent local draw = OSGL.draw local pixel = require(draw.pixel) local types = require(OSGL.types) return function(object: types.DrawableObject, startX: number, startY: number, stopX: number, stopY: number, thickness: number, color: types.Color) thickness = thickness or 1 color = color or types.color.BLACK -- Fixed a small bug local sizeX, sizeY = object.sizeX, object.sizeY local dx = stopX - startX local dy = stopY - startY local steps = math.max(math.abs(dx), math.abs(dy)) -- Calculating increments local xIncrement = dx / steps local yIncrement = dy / steps -- Drawing thickness offset pre-computation local halfThickness = math.floor(thickness / 2) local drawOffsets = {} for offsetX = -halfThickness, halfThickness do for offsetY = -halfThickness, halfThickness do table.insert(drawOffsets, {offsetX, offsetY}) end end local function drawThickPoint(px: number, py: number) for _, offset in ipairs(drawOffsets) do local pixelX = math.floor(px + offset[1] + 0.5) local pixelY = math.floor(py + offset[2] + 0.5) if pixelX >= 0 and pixelX < sizeX and pixelY >= 0 and pixelY < sizeY then pixel(object, pixelX, pixelY, color) end end end -- Drawing local x, y = startX, startY for step = 0, steps do drawThickPoint(x, y) x += xIncrement y += yIncrement end endKey Optimizations:
-
Thickness Handling:
- Pre-compute the offsets for thickness. This avoids recalculating the offsets in every call of
drawThickPoint.
- Pre-compute the offsets for thickness. This avoids recalculating the offsets in every call of
-
Condition Check:
- The condition to check if the pixel coordinates are in the drawable area remains unchanged. It ensures no unnecessary drawing is performed outside the bounds.
-
Local Variable Usage:
- Variables like
halfThicknesswere computed once rather than being computed in every loop iteration.
- Variables like
-
Avoiding Unnecessary Computation:
- The offset table (
drawOffsets) is created once, and the much smaller nested loop only calculates pixel positions once, which reduces redundant calculations.
- The offset table (
Additional Considerations:
-
If performance becomes critical with a large thickness value or extensive draw calls, consider looking into more efficient line drawing algorithms such as Bresenham's algorithm adapted for thickness. This is particularly useful for low-level graphic operations where performance might be a bottleneck.
-
Depending on the frequency of calls to this function and the typical values of thickness and coordinates, you may also benefit from further profiling or experimenting with different drawing strategies.
-
- User
when the circle is rotated sometimes, not all pixels inside are filled. fix.
return function(object: types.DrawableObject, centerX: number, centerY: number, radius: number, fill: types.Color?, stroke: types.Color?, strokeThickness: number?, rotation: number?) fill = fill or color.BLACK rotation = rotation or 0 stroke = stroke or color.TRANSPARENT strokeThickness = strokeThickness or 0
local radius = radius local strokeThickness = if stroke ~= color.TRANSPARENT then strokeThickness else 0 local sizeX, sizeY = object.sizeX, object.sizeY local radians = rotation * (math.pi / 180) local cosTheta = math.cos(radians) local sinTheta = math.sin(radians) local radiusSquared = radius * radius local totalRadius = strokeThickness + radius local strokeSquared = totalRadius * totalRadius for y = -totalRadius, totalRadius do local ySquared = y * y for x = -totalRadius, totalRadius do local distance = x * x + ySquared if distance <= strokeSquared then local pixelColor = if distance <= radiusSquared then fill else stroke local rotatedX = x * cosTheta - y * sinTheta local rotatedY = x * sinTheta + y * cosTheta local pixelX = math.floor(centerX + rotatedX + 0.5) -- Snap to nearest pixel local pixelY = math.floor(centerY + rotatedY + 0.5) -- Bounds check and pixel writing if pixelX >= 0 and pixelX < sizeX and pixelY >= 0 and pixelY < sizeY then pixel(object, pixelX, pixelY, pixelColor) end end end endend
- Assistant
The issue you're encountering, where not all pixels inside the rotated circle are filled, often arises from rounding errors during rotation and the pixel placement algorithm used. The snapping to the nearest pixel can lead to gaps if the circle is not rendered precisely, especially when rotation is involved.
Here are the changes you can make to ensure a circle is filled accurately, even when rotated:
- Use a proper point-in-circle equation: Rather than only checking if a pixel is within a squared radius from the center, consider points in terms of the rotated coordinates directly.
- Adjust how rotated points are calculated: Calculate the rotated position for each potential pixel before deciding if it should be drawn.
- Fill densely: Iterate through a slightly larger bounding box based on the total radius and apply a more precise distance check.
Here’s the modified function:
return function(object: types.DrawableObject, centerX: number, centerY: number, radius: number, fill: types.Color?, stroke: types.Color?, strokeThickness: number?, rotation: number?) fill = fill or color.BLACK rotation = rotation or 0 stroke = stroke or color.TRANSPARENT strokeThickness = strokeThickness or 0 strokeThickness = (stroke ~= color.TRANSPARENT) and strokeThickness or 0 local sizeX, sizeY = object.sizeX, object.sizeY local radians = rotation * (math.pi / 180) local cosTheta = math.cos(radians) local sinTheta = math.sin(radians) local radiusSquared = radius * radius local totalRadius = strokeThickness + radius local strokeSquared = totalRadius * totalRadius -- Loop over the bounding box for the total stroke radius for y = -totalRadius, totalRadius do for x = -totalRadius, totalRadius do -- Calculate the distance from the center using the original coordinates local distanceSquared = x * x + y * y -- Check if within the bounding box for stroke if distanceSquared <= strokeSquared then -- Calculate rotated coordinates local rotatedX = x * cosTheta - y * sinTheta local rotatedY = x * sinTheta + y * cosTheta -- Determine if we should fill or stroke local pixelColor = distanceSquared <= radiusSquared and fill or stroke -- Calculate final pixel position local pixelX = math.floor(centerX + rotatedX + 0.5) local pixelY = math.floor(centerY + rotatedY + 0.5) -- Bounds check and pixel writing if pixelX >= 0 and pixelX < sizeX and pixelY >= 0 and pixelY < sizeY and pixelColor ~= color.TRANSPARENT then pixel(object, pixelX, pixelY, pixelColor) end end end end endKey Changes and Improvements:
-
Adjusted Filling/Saving Logic:
- The check for whether to fill or stroke has been preserved, but the distance check ensures that any pixel that falls within the designated area is accounted for.
-
Bounding Box Check Enhanced:
- The bounding box now considers the entire stroke radius to avoid missing pixels, especially at the edges.
-
Transparent Pixel Handling:
- Before writing pixels to the object, it checks if the pixel color is not transparent to skip unnecessary writes.
-
Consistent Distance Calculation:
- Instead of checking distance after determining color, rotation is performed first, preserving the integrity of filling on the pixel grid.
With these adjustments, your filled circle should render more consistently, even when rotated, and avoid issues with gaps in coverage. Always test with various sizes and rotations to ensure that the behavior meets your expectations.
- User
can you make another one that draws a triangle with a optional stroke
- Assistant
Certainly! Below is a Lua function to draw a filled triangle with an optional stroke using the Open-Source Graphical Library (OSGL). The function accepts the coordinates of the triangle's three vertices, a fill color, and an optional stroke color with stroke thickness.
Triangle Drawing Function
return function(object: types.DrawableObject, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, fill: types.Color?, stroke: types.Color?, strokeThickness: number?) fill = fill or color.BLACK stroke = stroke or color.TRANSPARENT strokeThickness = strokeThickness or 0 local sizeX, sizeY = object.sizeX, object.sizeY local function drawLine(xStart, yStart, xEnd, yEnd, color) local dx = xEnd - xStart local dy = yEnd - yStart local steps = math.max(math.abs(dx), math.abs(dy)) local xIncrement = dx / steps local yIncrement = dy / steps local x = xStart local y = yStart for _ = 0, steps do local pixelX = math.floor(x + 0.5) local pixelY = math.floor(y + 0.5) if pixelX >= 0 and pixelX < sizeX and pixelY >= 0 and pixelY < sizeY then pixel(object, pixelX, pixelY, color) end x += xIncrement y += yIncrement end end -- Function to draw the filled triangle using scanline algorithm local function fillTriangle(x1, y1, x2, y2, x3, y3, color) -- Sort vertices by y-coordinate if y1 > y2 then x1, y1, x2, y2 = x2, y2, x1, y1 end if y1 > y3 then x1, y1, x3, y3 = x3, y3, x1, y1 end if y2 > y3 then x2, y2, x3, y3 = x3, y3, x2, y2 end if y1 == y3 then return end -- This is a flat triangle local invslope1 = (x2 - x1) / (y2 - y1) local invslope2 = (x3 - x1) / (y3 - y1) local invslope3 = (x3 - x2) / (y3 - y2) local curX1 = x1 local curX2 = x1 for y = y1, y3 do if y == y2 then curX1 = x2 end -- Draw the line between current x coordinates drawLine(math.floor(curX1 + 0.5), y, math.floor(curX2 + 0.5), y, color) curX1 += invslope1 curX2 += invslope2 end end -- Fill the triangle fillTriangle(x1, y1, x2, y2, x3, y3, fill) -- Draw stroke if stroke thickness is greater than 0 if strokeThickness > 0 and stroke ~= color.TRANSPARENT then drawLine(x1, y1, x2, y2, stroke) drawLine(x2, y2, x3, y3, stroke) drawLine(x3, y3, x1, y1, stroke) end endFunction Breakdown:
-
Parameters:
object: The drawable object where the triangle will be drawn.(x1, y1), (x2, y2), (x3, y3): Coordinates of the three vertices of the triangle.fill: Color to fill the triangle (defaults to black).stroke: Color for the triangle's outline (defaults to transparent).strokeThickness: Optional thickness for the stroke.
-
Line Drawing Function:
- A helper function
drawLineis used to draw lines between two points, allowing for reusability.
- A helper function
-
Filling the Triangle:
- The function
fillTriangleuses a basic scanline fill algorithm to fill the triangle with the specified color.
- The function
-
Stroke Drawing:
- If a stroke color is provided and the thickness is greater than 0, the triangle's edges are outlined.
Usage Example:
You can call this function with coordinates and colors as follows:
drawTriangle(object, 50, 50, 100, 150, 150, 50, color.RED, color.BLUE, 3)This would create a red filled triangle with a blue outline of thickness 3. Adjust the parameters as needed to suit your graphics context!
-